Reputation: 3844
I need to validate a input field which should contain at least x number of numeric characters.
eg: let say I need to input value has at least 5 numeric characters
12345 - valid
AB12345 - valid
123456 - valid
AB312312 - valid
asd - not valid
213 - not valid
First I tried with input.length
, but I don't know it will have a leading letters or not, so length
doesn't help for me
how should I do this validation with jquery or javascript ?
Upvotes: 0
Views: 458
Reputation: 3871
If
inputValue.replace(/[^0-9]/g,"").length < 5
then input field is invalid.
Upvotes: 1
Reputation: 2946
How about something like this
x = 5;
myString = "AB12345";
if (myString.replace(/[^0-9]/g,"").length >= x) {
alert('valid');
} else {
alert('not valid');
}
see this jsfiddle.
Upvotes: 1
Reputation: 19268
Let say you are looking at validating 5 numeric then you can use regular expression /(?=(?:[\d]){5})
.
What this expression does is that;
(?=)
means start looking ahead(?:[\d])
means match digits but don't capture them{5}
means (?:[\d])
(match digit) do 5 times"use strict";
let numbers = [ '12345', 'ABC12345', '123456', 'AB312312', 'asd', '213'];
numbers.forEach(number=> {
if (/(?=(?:[\d]){5})/.exec(number)) {
console.log(number + " is valid.");
};
});
Upvotes: 1
Reputation: 682
Using regular expressions will do the trick
function check(str,x){
var pattern = '^[a-zA-Z0-9]*[0-9]{'+x+'}[a-zA-Z0-9]*$';
if(str.match(pattern)) return true;
return false;
}
Upvotes: 1