简体   繁体   中英

Javascript regex validation?

So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. I also had a submit function that sends an email through the server. Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.

So I did the following but can't get it to work:

<script>
function validate(){
    var phone=/[0-9]*/;
    var x=document.forms["form"]["contactnum"].value;
    if (x!=phone){
        alert("Contact Number must be a valid phone number (no dashes)");
        return false;
    }

    else {
        alert("Thank you! We have received your information and will contact you shortly.");
        ajax('{{=URL('new_post')}}',['phone'], 'target');
            return false;
    }
}
</script>

The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. If I try to match it with any other var it will always say I'm not matching the [0-9]*. I already have written several complex regex's but really don't want to use anything on this simple form. I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null. I don't even care if they put in a "2" for the phone, just so long as it's a digit.

Thanks.

if ( x.match(/^[0-9]+$/) ) {
  // valid
} else {
  // invalid
}

That's not how you use a regular expression:

if (!phone.test(x)) ...

Also if you want to match a string with nothing but digits, try

var phone = /^\d*$/;

That will match the empty string too; use + instead of * if you want at least one digit.

You actually seem to have two questions in one here. For the first part, you haven't shown how you're using validate() , but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. For example, the following will not work:

$('#myform').submit(function(){
    validate();
});

But this would successfully stop the default submit process:

$('#myform').submit(function(){
    return validate();
});

validate() would return false, and then your handler returns the same.

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