我有一个单一的形式,根据单击哪个单选按钮(登录或注册),显示:
>电子邮件地址
>密码
要么:
<form id="myForm"> <input name="userAction" type="radio" value="login" checked="checked">Login</input> <br /> <input name="userAction" type="radio" value="signup">Sign Up</input> <div id="loginFields" style="display:none"> <!-- Login fields (email address and password) --> </div> <div id="signupFields" style="display:none"> <!-- Signup fields (name,age,email address,password) --> </div> </form>
我使用的是jQuery Validation plug-in,我想使用以下规则:
var signupRules = { emailAddressTextBox: { required: true,email: true },passwordTextBox: { required: true,minlength: 6,maxlength: 24,passwordValidationRule: true // custom regex added with $.validator.addMethod() } }; var loginRules = { nameTextBox: { required: true,maxlength: 50 },loginEmailAddressTextBox: { required: true,loginPasswordTextBox: { required: true,passwordValidationRule: true // custom regex added with $.validator.addMethod() },loginPasswordAgainTextBox: { required: true,equalTo: "#loginPasswordTextBox" passwordValidationRule: true // custom regex added with $.validator.addMethod() } };
如何基于以下动态添加正确的验证规则:
$("input[name='userAction']").change(function() { if ($("input[name='userAction']:checked" ).val() === "login") { // use loginRules } else { // use signupRules } });
我试过以下:
$("#myForm").validate({ rules: ($("input[name='userAction']:checked" ).val() === "login") ? loginRules : signupRules; });
解决方法
啊验证插件,总是那么棘手:
首先,我添加了id属性到所有的输入框。然后,我为你做了一个更改功能:
$("input[name='userAction']").change(function() { $('#signupFields').toggle(); $('#loginFields').toggle(); if ($("input[name='userAction']:checked").val() === "login") { removeRules(signupRules); addRules(loginRules); } else { removeRules(loginRules); addRules(signupRules); } });
function addRules(rulesObj){ for (var item in rulesObj){ $('#'+item).rules('add',rulesObj[item]); } } function removeRules(rulesObj){ for (var item in rulesObj){ $('#'+item).rules('remove'); } }
这就是它。参见这里的工作示例:http://jsfiddle.net/ryleyb/wHpus/66/
编辑:对我来说,非直观的部分是,我没有看到一个简单的方法添加/删除规则到整个窗体后,你调用validate,而不是你必须操纵单个表单元素。