为什么jquery表单验证不起作用? [英] why won't jquery form validation work?
问题描述
我有一个单击事件后在对话框内部打开的表单.我想知道我的jquery中是否有语法问题,我没有注意到.提交处理程序功能中的所有日志均未记录.
I have a form that opens up inside of a dialog after a click event. I'm wondering if there is a syntax problem in my jquery that I'm not noticing. None of the logs in the submit handler function are logging.
HTML:
<div id="dialog" title="Thanks For Volunteering">
<form>
<p>Please provide a contact number. It will only be shared with the comic</p>
<input id="number" name="number" type="text" />
<button id="submit" class="button">Submit</button>
</form>
</div>
JavaScript:
JavaScript:
$("form").submit(function(){
console.log("submit");
$('#number').validate({
rules: {
number : {
required: true
//customvalidation: true
}
},
messages: {
number : {
required: "enter a phone number"
}
},
submitHandler: function(form) {
// do other stuff for a valid form
//submit to parse
console.log("now validated");
var num = $('#number').val();
console.log("validated:" +' '+num);
}
});
});//closes submit
$.validator.addMethod("customvalidation",
function(value, element) {
return (/^[A-Za-z\d=#$%@_]+$/.test(value));
},
"Sorry, no special characters allowed");
推荐答案
.validate()
方法仅是插件的初始化.它永远不会在submit()
处理程序内部.只需将其附加到表单上,并在DOM准备就绪后将其称为一次.
The .validate()
method is only the initialization of the plugin. It never goes inside of a submit()
handler. Simply attach it to your form and call it once upon DOM ready.
$(document).ready(function() {
$('form').validate({
.....
您还需要将表单的<button>
元素更改为type="submit"
.
You will also need to change your form's <button>
element into a type="submit"
.
演示: http://jsfiddle.net/GJggc/1/
请在您之前的问题中再次参考此答案,该问题还将解决上述两个JavaScript问题以及详细的问题.说明:
Please refer back to this answer on your previous question, which also addresses the two JavaScript issues above along with a detailed explanation:
https://stackoverflow.com/a/18116262/594235
这篇关于为什么jquery表单验证不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!