Sophia111 Sophia111 - 4 months ago 9
HTML Question

Validating an 11-digit string input in JavaScript

I'm trying to make sure the input in a particular field is just an 11 digit number, however my if condition does not seem to be working:

Javascript:

<script>
function check() {
var x = document.forms["myform"]["mobile"].value;
if (!/^\d{11}$/.test(x)) {
myform.action="gender.html";
else {
myform.action="mobilerror.html"
}
}
</script>


And the HTML is:

<form id="myform" onsubmit="check();" >
<input class="input" type="text" name="mobile" required="required"
oninvalid="this.setCustomValidity('Number is empty')" oninput="setCustomValidity('')" />
</form>


Please help!

Answer

Your regular expression is working just fine. I think the error lies in the "if" condition. Try changing

if (!/^\d{11}$/.test(x)) {
 myform.action="gender.html";
else { 
 myform.action="mobilerror.html"
}

to this

if (/^\d{11}$/.test(x)) {
 myform.action="gender.html";
else { 
 myform.action="mobilerror.html"
}

Note that I just took off the negation in the expression.

Note: Assuming that the "mobilerror.html" is shown when the user didn't type the 11 digit as expected.

Comments