简体   繁体   中英

Why is my form still submitting even though it returns false?

I made this code which submits a form with a name and age field with a submit button. My code looks like this:

 function checkForm() { var name = document.forms["form"]["name"].value; var age = document.forms["form"]["age"].value; var regName = /^[AZ]*[az]{3,} $/; var regAge = /^[\\d.*]{1,} $/; if (name == regName && age == regAge) { return true; } else { return false; } } 
 <form name="form" action="register.php" method="POST" onsubmit="return checkForm()"> <p>Name:</p> <input type="text" name="name" id="name"> <br> <p>Age:</p> <input type="text" name="age" id="age"> <br> <br> <button type="submit" name="submit">Submit</button> </form> 

The name should be using only upper case and lower case letters and the age must be numerical and a positive integer.

Supposedly, when I entered the wrong data, the form should not return false but its returning true and sending me through to register.php. Is there something wrong with my code?

Try to add event.preventDefault(); when the data is invalid.

function checkForm(event){
    var name = document.forms["form"]["name"].value;
    var age = document.forms["form"]["age"].value;
    var regName = /^[A-Z]*[a-z]{3,} $/;
    var regAge = /^[\d.*]{1,} $/;

    if (name == regName && age == regAge){
        return true;

    } else{
   event.preventDefault();
        return false;
    }
}

Try evaluating regex With pattern.test('stringMethod')

function checkForm(event){
    var name = document.forms["form"]["name"].value;
    var age = document.forms["form"]["age"].value;
    var regName = /^[A-Z]*[a-z]{3,} $/;
    var regAge = /^[\d.*]{1,} $/;
    if (regName.test(name) && regAge.test(age)){
        return true;
    } else{
   event.preventDefault();
        return false;
    }
}

Form default behaviour is like that if you are calling a function on submit it will get submit. So you can call the function on button submit.

<button type="submit" name="submit" onsubmit="return checkForm()">Submit</button>

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