Reputation: 6946
I'm making a contact form which will be submitted with jQuery and I'm stuck on one simple validation.
I need to validate a field, which has to have at least x integers.
How can I do this?
p.s: please don't suggest validation plugin.
Thanks,
edit: This is what I've tried, but it's wrong I guess.
var numbercheck = /^(\w\d{7,14})?$/;
this is jsdiffle:
Upvotes: 0
Views: 307
Reputation: 41523
Try this
function hasUpTo5(strin){
if( string.replace(/[^0-9]/g, '').length <= 5){
return true
}else{
return false;
}
}
alert( hasUpTo5("fhsfbgurb3utn55nun44") );
Upvotes: 1
Reputation: 5563
Use regex
providing the range of numbers you can afford in your field
like \d{5,10} // Here 5 -10 is the range of numbers
function testContact(contact){
contact = contact.replace(/[a-z]*/g,"");
return (contact == contact.match(/\d{5,10}/))?true:false;
}
Upvotes: 2
Reputation: 10680
I'd write a small function that will do the job. Note that this function will return false if you have any non-int elements in the inputText
:-
function HasRequiredIntegers(inputText, requiredIntegers) {
var elems = inputText.split(/\s+/);
var intCount = 0;
var nonIntCount = 0;
for (i = 0; i < elems.length; i++) {
if (((parseFloat(elems[i]) == parseInt(elems[i])) && !isNaN(elems[i]))) {
intCount++;
}
else {
nonIntCount++;
}
}
return (intCount >= requiredIntegers && nonIntCount == 0);
}
Upvotes: 1
Reputation: 43124
To match a number of integers using a regex you'd need something like:
^((\d*)\s*)*$
Upvotes: 1