我正在尝试使用JavaScript验证HTML表单,并且我已经单独测试了所有验证函数,当我这样做时它们工作得很好,但是当我们将它们全部归还时出于某些原因只有validatename
和validateEmail
功能工作,我想知道是否有人可以给我提示我需要做些什么来使其工作?这是我的代码:
<script type="text/javascript">
function validatename()
{
var x = document.forms["feedback"]["fullname"].value;
if (x == "") {
alert('Name is not filled out');
return false;
}
} // validatename()
</script>
<script type="text/javascript">
function validateEmail()
{
var validemail = document.forms["feedback"]["email"].value;
if (/(.+)@(.+)\.(.+)/.test(validemail)){
return true;
}
else {
alert('Invalid email or email not filled out')
return false;
}
} // validateEmail
</script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
function agecheck() {
if($('input[name=age]:checked').length<=0)
{
alert("Please select your age");
return false;
}
} // agecheck
</script>
然后我通过这个在我的HTML正文中返回它们:
<form name = feedback onsubmit=" validateEmail() && validatename() && agecheck() ">
编辑:当我通过交换&amp;&amp;&amp;&amp;为所以我没有得到所有函数运行的短路评估,但由于某种原因,如果validatename和validateEmail都返回为非false,那么agecheck将不会运行,因此在它应该时不会发出警报。 / p>
EDIT2:好吧,出于某种原因,这是因为validatename要么返回false或者未定义,验证将不会返回,我只是修复它以返回true或false而不是undefined或false以某种方式固定它。谢谢大家的帮助
答案 0 :(得分:1)
以下示例并非旨在成为可行的解决方案。 (意思是我没有测试任何东西)
但这是我如何编写它的一个例子......只需要一个函数。
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
function validateForm(){
//validate the name
var x = document.forms["feedback"]["fullname"].value;
if (x == "") {
alert('Name is not filled out');
return; // script ends right here if the name field is empty.
}
// validate the email
var validemail = document.forms["feedback"]["email"].value;
if (!/(.+)@(.+)\.(.+)/.test(validemail)){
alert('Invalid email or email not filled out');
return; // script ends right here if the email field is incorrect.
}
// Validate the age
if($('input[name=age]:checked').length<=0){
alert("Please select your age");
return; // script ends right here if no age checkbox/radio field is checked.
}
// If the script wasn't halted already...
alert("All fine! Let's submit.");
//...
}
</script>
如果您愿意,现在可以将一个函数称为内联onsubmit
。我会以另一种方式做到......但是有很多方法可以验证表单。现在从您发布的代码中,我可以告诉您。
如果条件失败,要真正停止提交,请阅读preventDefault()
。
答案 1 :(得分:0)
尝试
<form name ="feedback" onsubmit="validateEmail();validatename();agecheck();">
OR
<form name ="feedback" onsubmit="function() { validateEmail(); validatename(); agecheck(); }">
答案 2 :(得分:0)
由于某种原因,validatename返回为undefine或false而不是true或false这一事实阻止了validateage在所有情况下都成功运行。在更改我的代码以使validatename返回true或false时,validateage函数现在按预期工作。