Reputation: 45
i am looking to filter my input so it can contain only numbers
re = /[^0-9]/;
if(!re.test(form.number.value)) {
alert("Member must contain only numbers. Please try again");
form.member.focus();
return false;
}
but it didn't work(if i gave for example an input 123fd, it don't give me the error) can anyone help me ?
Upvotes: 1
Views: 1283
Reputation: 531
Your regular expression matches anything but digits. When you're negating the test you're essentially saying "match digits" which means that you don't get the alert message for non-digit strings. E.g.:
!(/[^0-9]/.test('123'))
// true -> alert
!(/[^0-9]/.test('123fd'))
// false -> don't enter if clause
You can fix your code by just removing the exclamation mark in the if-statement. However, a clearer way of expressing your test would be as anubhava mentions:
if (/\D/.test(form.number.value)) {
// validation error
}
Where \D
matches non-digit characters.
Upvotes: 0
Reputation: 11943
if($input == intval($input)){
//OK
}
EDIT sorry it's javascript :
if(input == parseInt(input)){
//OK
}
Upvotes: 0
Reputation: 108
You can use HTML5 input type number to restrict only number entries:
<input type="number" name="someid" />
Upvotes: 3
Reputation: 785128
Since your regex is checking for non-digit therefore change negation in your if condition to:
re = /\D/;
if(re.test(form.number.value)) {
alert("Member must contain only numbers. Please try again");
// rest of code
}
instead of:
if(!re.test(form.number.value)) {...}
Upvotes: 2