如果Javascript中有任何错误,如何让表单不提交

时间:2013-05-09 14:49:52

标签: javascript forms

如果有任何错误,我不希望我的表单提交。但我仍然希望用户能够单击提交按钮来检查错误。目前它正在提交,然后告诉用户他或她做了什么错误。由于错误报告直接与提交按钮相关联,因此它也会非常快速地显示错误。那我该怎么办?

这是我的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
}

这是我的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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

如果表单无效,您可以执行类似这样的操作来停止提交按钮的默认行为。请注意,如果将preventDefault()位置于回调函数中,则无效:

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

submitBtn.addEventListener('click', validate);

function validate(event){
     // Validation code here

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

答案 2 :(得分:0)

看起来你已经建立了大量的验证功能。但是如果您在jquery submit method内使用它,则可以通过在条件中调用preventDefault()来确定用户是否继续。

根据我的建议,Daniel显然已经为您完成了JavaScript设置;)

答案 3 :(得分:-1)

你的表格应该是这样的:

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

这可以在jquery中直接完成:

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

你的函数validateForm()应该返回false,如果有任何错误,那么它将不会被提交