简体   繁体   English

jQuery表单验证无效

[英]JQuery Form Validation Does Nothing

This code isn't doing anything when I submit the form. 提交表单时,此代码没有执行任何操作。 What am I doing wrong? 我究竟做错了什么? In the HTML, an error message is shown or hidden based on a class. 在HTML中,基于类显示或隐藏错误消息。

I hope you can help me figure out this problem. 希望您能帮我解决这个问题。 Thanks in advance. 提前致谢。

 $(document).ready(function() { function validateForm() { var first_name = $("#first_name").value; var last_name = $("#last_name").value; var phone = $("#phone").value; var email = $("#email").value; var code = $("#vali_code").value; var ssn = $("#ssn").value; var income = $("#nm_income").value; var error = $(this).find("span.error_txt").removeClass(".hidden").addClass(".show"); var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/; if (first_name === "") { error; } if (last_name === "") { error; } if (email === "" || email !== emailReg) { error; } if (phone === "" || phone < 9) { error; } if (ssn === "" || ssn > 4) { error; } if (income === "") { error; } if (code === "") { error; } return true; } }); 

If you call the function in inline event onsubmit you should add return keyword to the function call in your form inline event like : 如果onsubmit联事件onsubmit调用函数,则应在表单内联事件中将return关键字添加到函数调用中,例如:

<form onsubmit='return validateForm()'>

But I think the main problem comes from the .value in your code it should be replaced by .val() since the value isn't an attribute of jQuery objects. 但我认为主要问题来自代码中的.value ,应将其替换为.val()因为该value不是jQuery对象的属性。

My suggestion is to attach the submit event in the JS code like the snippet below. 我的建议是将Submit事件附加在JS代码中,如下面的代码片段所示。

NOTE: The argument passed to removeClass() and addClass() methods shouldn't contains dot . 注意:传递给removeClass()addClass()方法的addClass()不应包含dot . at the start. 在开始时。

 $(function() { $('form').on('submit', validateForm); }) function validateForm() { var first_name = $("#first_name").val(); var last_name = $("#last_name").val(); $(this).find("span.error_txt").removeClass("hidden").addClass("show"); if (first_name === "") { return false; } if (last_name === "") { return false; } alert('Form will be submited.'); return true; } 
 .hidden { display: none; } .show { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input id='first_name'><br> <input id='last_name'><br> <button>Submit</button> <span class="error_txt hidden">Error occurred check you form fields again.</span> </form> 

如果表单无效,则需要return false ,否则将被提交。

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

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