简体   繁体   中英

validate mobile number in javascript

I want to validate my mobile number using javascript and my code is:

function checkLength(){
    var textbox = document.getElementById("textbox");
    if(textbox.value.length == 10){
        alert("success");
    }
    else{
        alert("mobile number must be 10 digits long");
        textbox.focus();
        return false;
    }
}

and calling function is: <input type="text" name="Contact-No." id="textbox" required >Contact(Mobile No.)

<input type="submit" value="Submit" onclick="checkLength()">
<input type="text" name="Contact-No." id="textbox" required >Contact(Mobile No.)

<input type="submit" value="Submit" onclick="checkLength()">

All works fine but after showing alert message it should be return on same page but it takes me to some other blank page.

1) Your form needs to prevent the default submit action so that if you find error the form doesnt actually submit.. you should hook into the onsubmit event in your form.

an example assuming you've included jQuery 1.7+ on the page

html

<form id="myform" action="/">
  <input type="text" name="Contact-No." id="textbox" />   
  Contact(Mobile No.)<br><br>
  <input type="submit" value="Submit" id="submit" />
</form>

javascript

$("#myform").on("submit",function(e){
    if(checkLength()==false){
        alert('prevent form submit');
        e.preventDefault();
    }else{
        alert('form submits as normal');
    }
});

function checkLength(){
    var textbox = document.getElementById("textbox");
    if(textbox.value.length == 10){
        alert("success");
        return true;
    }
    else{
        alert("mobile number must be 10 digits long");
        textbox.focus();
        return false;
    }
}

example at:

http://jsfiddle.net/Lqbn6unp/

remove the onClick event from button and add onSubmit to <form..> . Something like <form onSubmit='return checkLength();>' .

As pointed out elsewhere, the listener should be on the form's submit handler since the form can be submitted without pressing the submit button. Also, you can reference form controls as named properties of the form, which is more efficient than using getElementById and means the control doesn't need an ID.

So pass a reference to the form from the listener, eg

In the form:

<form onsubmit="return checkLength(this)" ... >
  <input type="text" name="Contact-No." required >Contact(Mobile No.)

then in the function:

function checkLength(form) {
    var textbox = form['Contact-No'];

    if (textbox.value.length == 10) {
        alert("success");

    } else {
        alert("mobile number must be 10 digits long");
        textbox.focus();
        return false;
    }
}

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