I'm using this code for validating the phone number:
<script>
$("#Phone").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
var val = Phone.value
if (/^\d{11}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be eleven digits")
Phone.focus()
return false
}
</script>
I want the user to input only 11 digits and if it doesn't, it alerts user that they have to input 11 digits and sets the value to null.
The problem is, when it alerts that the number is less than 11 digits, it doesn't set the value to null.
I know you're asking for a JS solution but this can be done with the new attributes in html5
<input type="tel" pattern="[0-9]{11}" placeholder="Your 11 digit phone number..." required/>
Fiddle here: https://jsfiddle.net/7owhrssr/
This code can help you, cause may you have problem with regex
var regex =/^\d+$/;
if (regex.test(val)) {
alert('value is ok, use it');
}else{
alert('Invalid number; must be eleven digits');
Phone.focus()
return false}