使用jQuery Validator验证动态生成的表单 [英] Validate dynamically generated form with jQuery Validator
问题描述
很抱歉继续问这个问题,但我无法弄清楚.我已将问题减少到最低限度.
Sorry for keep asking this, but I just can't figure it out. I've reduced the question to just the bare minimum.
如何验证动态生成的表单?下面是我的尝试,但可以看到,它显示为通过验证.
How can I validate a dynamically generated form? Below is my attempt, but as seen, it shows up as passing validation.
https://jsfiddle.net/j2pgobze/1/
<form id="myForm">
<input type="text" name="email" id="email" value="bademail" >
</form>
<button id="validate">validate</button>
var myValidateObj = {
rules: {
email: {
email: true
}
}
};
$(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#validate').click(function () {
//Validate the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
console.log('Option 1', $('#myForm'), $('#email'), $('#email').val(), validate1.element('#email'), $('#email').valid(), $('#myForm').valid());
//Validate dynamically created form
var input = $('<input />', {
type: 'text',
name: 'email',
value: 'bademail'
});
//input.prop('value', 'bademail');
var form = $('<form />').append(input);
var validate = form.validate(myValidateObj);
console.log('Option 2', form, input, $('#email').val(), validate.element(input), input.valid(), form.valid());
});
});
推荐答案
-
按钮必须位于
form
内并且为type="submit"
,以便插件捕获点击.
The button needs to be inside the
form
and be atype="submit"
in order for the plugin to capture the click.
请勿将.validate()
放在click
处理程序中(请参见第1项).它仅用于初始化表单上的插件.例外,下面我们在click
处理程序中创建新表单,然后立即在新表单上调用.validate()
.
Do not put .validate()
within a click
handler (See item 1). It's only used to initialize the plugin on a form. Exception, below we are creating the new form within a click
handler and then immediately calling .validate()
on the new form.
有了这两个小的更改,就可以在静态表单上进行验证: jsfiddle.net/j2pgobze/3/
With these two small changes, the validation on the static form is working: jsfiddle.net/j2pgobze/3/
- 为清楚起见,我重写了您的DOM操作代码.我只是复制了表单的HTML,并为其指定了新的ID: http://jsfiddle.net/zem84tfp/
$(function () {
// INITIALIZE plugin on the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
$('#newform').one('click', function () {
// code here to create new form; give it new ID
// do not duplicate ID on anything else
// INITIALIZE plugin on the new form
var validate = $('#myForm2').validate(myValidateObj);
});
});
这篇关于使用jQuery Validator验证动态生成的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!