简体   繁体   中英

JavaScript validation for OPTIONAL mobile no

I have a registration form, where there is a MobileNo field, where the user is supposed to give their mobile number, but this field is optional as the user may choose NOT to give his/her mobile number.
In the database table I have kept the ALLOW NULL option for this field.

Now I want to use JavaScript validation on this field, so that the user can only type an integer value and that only 10 digits, if he/she chooses to give his/her mobile number.
The problem is, when I am writing the code for this, then when I am keeping the mobile field blank, it's showing the error as the JavaScript validation is working on it.

My JavaScript code is the following:

function f1() {
if (document.form2.mobile.length!=10 || isNan(document.form2.mobile) {
    alert("Mobile No must be NUMERIC and 10 digit long");
    return false;   
}

Is there any solution as these validation will work only if the user chooses to type his/her mobile no else if its blank, the registration will get completed.

Wrap it in another condition, like so :

function f1() {
    if(document.form2.mobile.value !== "") {
        if (document.form2.mobile.length!=10 || isNan(document.form2.mobile)
        {
            alert("Mobile No must be NUMERIC and 10 digit long");
            return false;
        }
    }
}

Regex option:

if (!/^$|^\d{10}$/.test(document.form2.mobile.value)) {
    alert("Mobile No must be NUMERIC and 10 digit long");
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM