简体   繁体   中英

How to get a form to not submit if there are any errors in Javascript

I don't want my form to submit if there are any errors. But I still want the user to be able to click the submit button to check for errors. At the moment it is submitting and then telling the user what errors he or she made. It is also showing the error very quickly as the error report is directly tied to the submit button. So what do I do?

Here is my Javascript:

function validateUserName()
{
    var u = document.forms["NewUser"]["user"].value
    var uLength = u.length;
    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if (u == null || u == "")
    {

        $("#ErrorUser").text("You Left the Username field Emptyyy");
        return false;
    }
    else if (uLength <4 || uLength > 11)
    {
        $("#ErrorUser").text("The Username must be between 4 and 11 characters");
        return false;
    }
    else if (illegalChars.test(u)) 
    {
        $("#ErrorUser").text("The Username contains illegal charectors men!");
        return false;
    }
    else
    {
        return true;
    }
}

function validatePassword()
{
    var p = document.forms["NewUser"]["pwd"].value
    var cP = document.forms["NewUser"]["confirmPwd"].value
    var pLength = p.length;
    if (p == null || p == "")
    {
        $("#ErrorPassword1").text("You left the password field empty");
        return false;
    }
    else if (pLength < 6 || pLength > 20)
    {
        $("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
        return false;
    }
    else if (p != cP)
    {
        $("#ErrorPassword1").text("Th passwords do not match!");
        return false;
    }
    else
    {
        return true;
    }
}

function validateEmail()
{
    var e = document.forms["NewUser"]["email"].value
    var eLength = e.length;
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    if (eLength == "" || eLength == null) 
    {

        $("#ErrorEmail").text("You left the email field blank!");
        return false;
    } 
    else if (e.match(illegalChars)) 
    {

        $("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
        return false;
    } 
    else 
    {
        return true;
    }
}
function validateFirstName()
{
    var f = document.forms["NewUser"]["fName"].value;
    var fLength = f.length;
    var illegalChars = /\W/;

    if(fLength > 20)
    {
        $("#ErrorFname").text("First Name has a max of 20 characters");
        return false;
    }
    else if (illegalChars.test(f))
    {
        $("#ErrorFname").text("Numbers,letter and underscores in first name only");
        return false;
    }
    else 
    {
        return true;
    }


}

function validateLastName()
{
    var l = document.forms["NewUser"]["lName"].value;
    var lLength = l.length;
    var illegalChars = /\W/;

    if(lLength > 100)
    {
        $("#ErrorLname").text("Last Name has a max of 100 characters");
        return false;
    }
    else if (illegalChars.test(f))
    {
        $("#ErrorLname").text("Numbers,letter and underscores in last name only");
        return false;
    }
    else 
    {
        return true;
    }


}

function validateForm()
{
    //call username function
    validateUserName();

    //call password function
    validatePassword();

    //call email function
    validateEmail();

    //call first name function
    validateFirstName();

    //call first name function
    validateLastName();

    //perform form input validation and submit data
}

And here is my HTML:

    <table id = "SignUpTable">

        <form name = "NewUser" id = "your-form"> 
            <tr>
            <td id = "ErrorUser"></td>
            <td class = "FieldName">Username:</td> 
            <td class = "TextField"><input type = "text" name = "user"/></td> 
            </tr>
            <tr>
            <td></td>
            <td class = "Information"><em>Must be 4-11 characters.<br/>Only numbers, letters and underscores.</em></td>
            </tr>

            <tr>
            <td id = "ErrorEmail"></td>
            <td class = "FieldName">Email:</td> 
            <td class = "TextField"><Input type = "text" name = "email"/></td>
            <tr>
            <td></td>
            <td  class = "Information"><em>We need this to verify your account.</em></td>
            </tr>

            <tr>
            <td id = "ErrorPassword1"></td>
            <td class = "FieldName">Password:</td>
            <td class = "TextField"><input type = "password" name = "pwd"/></td>
            <tr>
            <td></td>
            <td  class = "Information"><em>6-20 characters</em></td>
            </tr>

            <tr>
            <td id = "ErrorPassword2"></td>
            <td class = "FieldName">Confirm Password:</td>
            <td class = "TextField"><input type = "password" name = "confirmPwd"/></td>
            <tr>
            <td></td>
            <td  class = "Information"><em>just in case you didn't make mistakes!</em></td>
            </tr>



            <tr>
            <td id = "ErrorFname"></td>
            <td class = "FieldName">First Name:</td>
            <td class = "TextField"><input type = "text" name = "fName"/></td>
            <tr>
            <td></td>
            <td  class = "Information"><em>optional</em></td>
            </tr>


            <tr>
            <td id = "ErrorLname"></td>
            <td class = "FieldName">Lastname:</td>
            <td class = "TextField"><input type = "text" name = "lName"/></td>
            <tr>
            <td></td>
            <td  class = "Information"><em>(optional)</em></td>
            </tr>

            <tr>
            <td><input type = "submit" value = "Submit"/></td>
            </tr>

            </form>
    </table>
    <script>
    $('#your-form').submit(validateForm);
    </script>

http://api.jquery.com/submit/

function validateForm()
{
    var valid = true;
    //call username function
    valid = valid && validateUserName();

    //call password function
    valid = valid && validatePassword();

    //call email function
    valid = valid && validateEmail();

    //call first name function
    valid = valid && validateFirstName();

    //call first name function
    valid = valid && validateLastName();

    return valid;
}
$('#your-form').submit(validateForm);

You can do something like this to stop the default behavior of the submit button if the form is invalid. Note that this will not work if you put the preventDefault() bit inside a callback:

var submitBtn = document.getElementByTagName('submit')[0];

submitBtn.addEventListener('click', validate);

function validate(event){
     // Validation code here

     if(!isValid){
         event.preventDefault();
         event.stopPropagation();
     }
}

It looks like you have established plenty of validation functions. But if you use that inside a jquery submit method , you could then determine if the user proceeds or not, by calling preventDefault(), in a condition.

Daniel has obviously done the JavaScript setup for you, based on my suggestion ;)

Your form should be like this:

<form name="myForm" action="yourpage.php" onsubmit="return validateForm()" method="post">
.....
</form>

This can be done in jquery aswell directly:

$('#myForm).submit(validateForm);

your function validateForm() should return false if there are any errors so it won't get submitted

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