gpt4 book ai didi

javascript - 表单验证规则动态变化

转载 作者:行者123 更新时间:2023-11-30 19:42:19 24 4
gpt4 key购买 nike

var mandatory = {
emailAddressTextBox: {
required: true,
email: true
},
passwordTextBox: {
required: true,
minlength: 6,
maxlength: 24,
}
};

var nonmandatory = {
nameTextBox: {
required: true,
maxlength: 50
},
loginEmailAddressTextBox: {
required: true,
email: true
},
loginPasswordTextBox: {
required: true,
minlength: 6,
maxlength: 24,
},
loginPasswordAgainTextBox: {
required: true,
minlength: 6,
maxlength: 24,
equalTo: "#loginPasswordTextBox"
}
};

$("#myForm").validate({
rules: ($("input[name='country']").val() === "US") ? mandatory : nonmandatory;
});

我想根据国家名称动态更改 ajax 中的表单验证规则。

假设是英国:

only email and password should be mandatory.

或者如果是美国:

along with email, First name and last name should be mandatory.

我是 Ajax 新手。

谁能帮帮我?

提前致谢!

最佳答案

尝试这个答案...在验证规则中而不是 required:true 你必须使用这个函数

required: function(element) {
if ($("#country option:selected").val()== '1') {
return false;
}
else {
return true;
}
}

$(document).ready(function () {


$("#form").validate({
rules: {
"name": {
required: function(element) {
if ($("#country option:selected").val()== '1') {
return false;
}
else {
return true;
}
},
minlength: 5
},
"email": {
required: function(element) {
if ($("#country option:selected").val()== '1') {
return true;
}
else {
return true;
}
},
email: true
},
"password": {
required: function(element) {
if ($("#country option:selected").val()== '1') {
return true;
}
else {
return true;
}
},
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
},
"password": {
required: "Please, enter password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});

});
body {
padding: 20px;
}

label {
display: block;
}

input.error {
border: 1px solid red;
}

label.error {
font-weight: normal;
color: red;
}

button {
display: block;
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<select id="country">
<option value="1">US</option>
<option value="2">UK</option>
</select>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="email" name="email" id="email" />
<label for="name">Password</label>
<input type="text" name="password" id="password" />
<button type="submit">Submit</button>
</form>

关于javascript - 表单验证规则动态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55274674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com