如何在不提交表单的情况下验证表单

时间:2015-03-25 18:14:17

标签: javascript

当我按下“提交”按钮时,我需要在表单提交之前验证表单。我知道我应该使用preventDefault,但我不确定如何正确使用它:

function validateName() {
    var name = form.firstname.value;

    if (name == "") {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
    } else if (/[0-9]/.test(name)) {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
    } else {
        document.getElementById("firstnameInvalid").style.visibility = "hidden";
    }
}


<form name="form" method="post" onsubmit="return validate(this)">

    <p>First Name:
        <input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name" /> 
        <span id="firstnameInvalid" style="color:red; visibility:hidden"> Name is Invalid </span>
    </p>

3 个答案:

答案 0 :(得分:0)

您可以通过在验证码中添加return语句来停止表单。当函数返回onsubmit时,false将停止提交表单。

答案 1 :(得分:0)

正如其他人所说,在onsubmit回调中返回false会阻止提交表单。

var form = document.getElementById( 'idgoeshere' );

form.onsubmit( function() {
    // validate here
    return false;
});

答案 2 :(得分:0)

您的validate()必须返回真值或假值才能使用onsubmit="return validate(this)"

尝试类似

的内容
function validate(variable)
{
    if(condition) //add a condition to validate
    {
        return false; //if condition are met, return false and do not submit
    }
    //you can create more than one condition following this logic.
    return true; //if none of the conditions are met, he return true and submit
}
相关问题