简体   繁体   English

JavaScript表单验证,如果无效则不提交

[英]Javascript form validation and if invalid no submission

Frnds i need some help.. In this code i have validated the 2 textboxes. 我需要一些帮助。在此代码中,我验证了2个文本框。 The help i need is once no data has been entered in the boxes the form should not goto check.php but with an javascript alert: Invalid Data I need this in Javascript... 我需要的帮助是,一旦在方框中没有输入任何数据,表单就不应该转到check.php,而是带有JavaScript警报:无效的数据,我需要用Javascript编写...

function f1()
{
    var v1=document.getElementById("uname").value;
    var v2=document.getElementById("pass").value;
if(v1=="" || v2=="")
alert("Please Fill It..!");

}

Username:<input type="text" id="uname" placeholder="username" title="Enter your Username" name="uname"/>
Password:
<input type="password" id="pass" placeholder="password" title="Enter your password" name="pass"/>
<input type="submit" value="Login"/>
<input type="reset" value="clear"/>

</form>

Try this: 尝试这个:

function f1()
{
    var v1=document.getElementById("uname").value;
    var v2=document.getElementById("pass").value;
    if(v1=="" || v2=="") 
    {
         alert("Please Fill It..!");
         return false;
    }
}

The problem with your function is that by default it returns true and form is submitted. 您的函数的问题在于,默认情况下它返回true并提交表单。 You need to return false in order to prevent form submit. 您需要返回false以防止表单提交。

You can use the attribute onSubmit which will run the javascript in it. 您可以使用onSubmit属性,该属性将在其中运行javascript。 If it returns a falsy value, the submit won't be made, but if it returns true , the submit will be made. 如果返回假值,则不会进行提交,但是如果返回true ,则将进行提交。

<form method="POST" onSubmit="return f1()">
Username:<input type="text" id="uname" placeholder="username" title="Enter your Username" name="uname"/>
Password:
<input type="password" id="pass" placeholder="password" title="Enter your password" name="pass"/>
<input type="submit" value="Login"/>
<input type="reset" value="clear"/>

</form>

f1 has to be a function that returns true or false f1必须是返回truefalse的函数

you need to register your f1() as form onSubmit event handler. 您需要将f1()注册为onSubmit事件处理程序。

<form action="formaction" method="post" onsubmit="f1()">
Username:<input type="text" id="uname" placeholder="username" title="Enter your Username" name="uname"/>
Password:
<input type="password" id="pass" placeholder="password" title="Enter your password" name="pass"/>
<input type="submit" value="Login"/>
<input type="reset" value="clear"/>
</form>

function f1()
{
    var v1=document.getElementById("uname").value;
    var v2=document.getElementById("pass").value;
    if(v1=="" || v2=="") return false;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM