我有一个表单,根据单击的单选按钮(登录或注册),显示:
或:
单击单选按钮可切换登录/注册字段的可见性:
<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,
email: true
},
loginPasswordTextBox:
{
required: true,
minlength: 6,
maxlength: 24,
passwordValidationRule: true // custom regex added with $.validator.addMethod()
},
loginPasswordAgainTextBox:
{
required: true,
minlength: 6,
maxlength: 24,
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;
});
但由于我的登录字段是默认显示,因此其验证有效,但注册方案不起作用;它想要出于某种原因验证登录字段。我错过了什么吗?
答案 0 :(得分:55)
啊验证插件,总是那么棘手:(
首先,我在所有输入框中添加了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/
编辑:对我而言,非直观的部分是,在您致电{后,我看不到在整个表单中添加/删除规则的简单方法{1}},而你必须操纵单个表单元素。
答案 1 :(得分:34)
或者您可以使用依赖属性。
http://jqueryvalidation.org/category/plugin/ 搜索取决于
示例:根据需要指定联系人元素和电子邮件地址,后者取决于通过电子邮件检查联系人的复选框。
$(".selector").validate({
rules: {
contact: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email:checked")
}
}
}
}
});
答案 2 :(得分:8)
如果您想使用新设置(规则,消息等)再次呼叫验证 调用
$('#formid').removeData('validator')
这将删除表单的验证,然后使用新设置再次初始化
答案 3 :(得分:7)
这篇文章来自几年前,但由于它已被多次查看,我认为现在jQuery Validation插件允许我们阅读,添加和删除规则会很有用。
一些例子:
打印#myField
附带的所有规则:
console.log($('#myField').rules());
删除不需要的规则:$('#myField').rules('remove', 'min');
添加新规则:$('myField').rules('add', {min: 10});
所以说如果你想动态更新所需的最小值。您可以在之后立即拨打remove
和add
:
// Something happened. The minimum value should now be 100
$('#myField').rules('remove', 'min');
$('#myField').rules('add', {min: 100});
可在此处找到更多信息:https://jqueryvalidation.org/category/plugin/#-rules()
答案 4 :(得分:3)
现在有一个选项可以忽略基于选择条件的字段,例如不可见或禁用,这样您就不必更改规则集:
.validate({
ignore: ":not(:visible),:disabled",
...
答案 5 :(得分:3)
试试这个..
rules: {
address: {
required: {
depends: function(element) {
if (....){
return true;}
else{
return false;}
}
}
}
}
来自here的信用。
答案 6 :(得分:1)
跟踪验证对象并直接删除/替换规则。适用于v1.13.0
var validation = $('#form1').validate(); //Keep track of validation object
//Rule set 1
var validationRulesLogin = {
headerEmail: {
required: true,
email: true
},
headerPassword: "required"
};
var validationMessagesLogin = {
headerEmail: {
required: "Please enter your email address.",
email: "Not a valid email address."
},
headerPassword: "Please enter your password."
};
//Rule set 2
var validationRulesSignup = {
signupEmail: {
required: true,
email: true
},
signupPassword: "required",
signupPassword2: {
equalTo: "#phBody_txtNewPassword"
}
};
var validationMessagesSignup = {
signupEmail: {
required: "Please enter your email address.",
email: "Not a valid email address."
},
signupPassword: "Please enter your password.",
signupPassword2: "Passwords are not the same."
};
//Toggle rule sets
function validatingLoginForm(){
validation.resetForm();
validation.settings.rules = validationRulesLogin;
validation.settings.messages = validationMessagesLogin;
}
function validationSignupForm(){
validation.resetForm();
validation.settings.rules = validationRulesSignup;
validation.settings.messages = validationMessagesSignup;
}
答案 7 :(得分:0)
看看我的回答https://stackoverflow.com/a/20547836/1399001。 它包括一个工作的jsfiddle。 在你的例子中将是这样的:
$("input[name='userAction']").change(function() {
var settings = $("#myForm").validate().settings;
if ($("input[name='userAction']:checked" ).val() === "login") {
$.extend(settings, {
rules: loginRules
});
} else {
$.extend(settings, {
rules: signupRules
});
}
$("#myForm").valid();
});
答案 8 :(得分:0)
我有一个类似的问题并通过添加&#34; requiredForLogin&#34;来解决它。所有登录文本框的类,以及&#34; requiredForSignUp&#34;所有注册文本框的类。
然后使用jQuery的toggleClass和jQuery.validate的addClassRules打开和关闭规则,具体取决于按下的按钮。
function EnableAllValidation() {
// remove the jquery validate error class from anything currently in error
// feels hackish, might be a better way to do this
$(".error").not("label").removeClass("error");
// remove any the 'disabled' validation classes,
// and turn on all required validation classes
// (so we can subsequently remove the ones not needed)
$(".requiredForLoginDisabled").toggleClass("requiredForLoginDisabled requiredForLogin");
$(".requiredForSignUpDisabled").toggleClass("requiredForSignUpDisabled requiredForSignUp");
}
function EnableLoginValidation() {
// reenable all validations
// then disable the signUp validations
EnableAllValidation();
$(".requiredForSignUp").toggleClass("requiredForSignUpDisabled requiredForSignUp");
}
function EnableSignUpValidation() {
// reenable all validations
// then disable the login validations
EnableAllValidation();
$(".requiredForLogin").toggleClass("requiredForLoginDisabled requiredForLogin");
}
$(document).ready(function () {
$("input[value='login']").click(function () {
EnableLoginValidation();
});
$("input[value='signup']").click(function () {
EnableSignUpValidation();
});
$("#myForm").validate();
jQuery.validator.addClassRules({
requiredForSignUp: {
required: true
},
requiredForLogin: {
required: true
}
});
});
答案 9 :(得分:0)
这可以通过更新 .validate().settings.rules
下面的密码字段示例片段,将添加所需规则。
$('#myForm').validate().settings.rules.password = {required: true};
答案 10 :(得分:-2)
以下代码工作精湛......
.validate({
ignore: ":not(:visible),:disabled",
...