问题描述
我已经设法验证我的字段,所以它总是四位数,但我需要验证,以便它始终是一个数字。我尝试添加这段代码,但它无法正常工作。
I've managed to validate my field so it is always four digits, but i need to validate so that it is always a number. I tried adding this block of code but it doesn't work properly.
if (!(document.ExamEntry.cand.value.match(numbers))) {
msg += "Only use numeric characters \n";
document.ExamEntry.cand.focus();
document.getElementById('cand').style.color = "red";
result = false;
}
这将允许四位数组合,如9a9a或!2#3等。
我添加了这样的数字变量;
This will allow four digit combinations like 9a9a or !2#3 etc.I added the "numbers" variable like this;
var numbers = /[0-9]/;
进行此验证的更好方法是什么?
What is a better way of doing this validation?
推荐答案
假设你在这里得到你的价值
Let's say you get your value here
var val = document.ExamEntry.cand.value;
然后,如果你想让它成为4位数的东西,就这样做吧
Then if you want it to be something with 4 digits inside, just do this
var itIsNumber = /^\d{4}$/.test(val); // true if it is what you want
如果你希望它是1到4位的东西在里面,只需这样做
if you want it to be something with 1 to 4 digits inside, just do this
var itIsNumber = /^\d{1,4}$/.test(val); // true if it is what you want
此处有更多示例和详细信息 - >
more examples and details here --> Regular Expressions
这篇关于如何验证文本字段,使其只能包含四位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!