0

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>
4
  • You mean errors or validation issues? If you mean errors as in syntax errors, divide by 0 errors, etc, wrap the part that could throw an error in try/catch and return false in the catch. If you mean the submit still happens after validation returns false, it may depend on how you registered your event, you might want to post that part of the code or html, too Commented May 9, 2013 at 14:53
  • Okay, going to add the HTML. Commented May 9, 2013 at 15:02
  • onsubmit must be onsubmit= "return validateForm()" and your validateForm must return false in case of errors otherwise it does not stop Commented May 9, 2013 at 15:05
  • Just change your html to onsubmit= "return validateForm()" and then use daniels validateForm() Commented May 9, 2013 at 15:08

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

11 Comments

Please refresh the page. I had a syntax error, but I fixed it.
Be sure that your form has an id 'your-form', your form must look like <form id="your-form"
Can I not just use the form name?
You can. But use the right selector. $('form[name=formname]')
I did it with ID, and it still does not seem to work, I posted the HTML above and if I remove the onSubmit tag from my actual HTML form and you use your JS, then it just does nothing when I press submit.
|
2

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();
     }
}

Comments

0

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 ;)

2 Comments

It is still not working though. The error messages are not being displayed when it is wrong, and it is still submitting regardless.
We answered at the same time... I didn't see your answer. You could provide better answers if you paste some code sample, do it next time.
0

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

1 Comment

your function validateForm() should return false when there are errors,otherwise it just continues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.