Reputation: 21
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;
}
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?
Upvotes: 2
Views: 11644
Reputation: 4968
Let's say you get your value here
var val = document.ExamEntry.cand.value;
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
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
Upvotes: 6
Reputation: 2930
/^[0-9]{4}$/
for four numbers
/^[0-9]*$/
for any amount of numbers
/^[0-9]+$/
for at least one number
Upvotes: 3