我们在单个页面应用程序中有多个表单。单个表单有各自的保存按钮,单个表单在其上进行验证,如果有效(使用jquery验证器.valid()方法),则记录将保存在数据库中,该工作正常。
我们在这里面临的问题是,当最后一个表单是最终提交时,当我们尝试使用.valid()方法验证所有其他表单以进行验证时,无论错误的验证如何,它总是返回true。 / p>
$("#submitForm").submit(function(event) {
$("#educationForm").validate();
console.log($("#educationForm").valid());
});
即使教育表格无效,控制台也会给出正确的
请帮助我们解决这个问题。
此致 Suvojit
答案 0 :(得分:3)
valid() function not working on submit
The .valid()
method was designed to programmatically trigger a validation test. When you click "submit", the plugin is automatically doing a validation test, so there's no point in also calling .valid()
on the "submit" event.
I think you may be misunderstanding the basic usage...
$("#submitForm").submit(function(event) {
$("#educationForm").validate(); // <- INITIALIZES PLUGIN
console.log($("#educationForm").valid()); // <- TEST VALIDATION
});
You would never put .validate()
inside of an event handler other than a DOM ready handler. The .validate()
method is how the plugin is initialized.
After it's initialized properly, the plugin automatically captures the click event of the submit button.
By putting it inside of a .submit()
handler, you're interfering with the plugin, which is already trying to capture the exact same event.
Put inside of the DOM ready event handler instead...
$(document).ready(function() {
$("#educationForm").validate(); // <- INITIALIZES PLUGIN
console.log($("#educationForm").valid()); // <- TEST VALIDATION
});
Working DEMO: http://jsfiddle.net/2vugwyfe/
OR: http://jsfiddle.net/2vugwyfe/1/
The validation test is automatically triggered by any type="submit"
element.
If you need to trigger a validation test by clicking another type of element, then use a custom .click()
handler...
$(document).ready(function() {
$("#educationForm").validate(); // <- INITIALIZES PLUGIN
$("#button").on('click', function() {
$("#educationForm").valid(); // <- TEST VALIDATION
});
});
DEMO 2: http://jsfiddle.net/pdhvtpdq/
EDIT:
To check if a different form is valid, use the .valid()
method inside of the submitHandler
option.
In this example, when the submitHandler
for "Form A" fires, it then checks if "Form B" is valid before allowing a submission.
$(document).ready(function() {
$("#form_A").validate({ // initialize plugin on Form A
submitHandler: function(form) { // fires when Form A is valid
if($("#form_B").valid()) { // tests if Form B is valid
$(form).submit(); // submit Form A
}
}
});
});