表单验证规则动态变化
Posted
技术标签:
【中文标题】表单验证规则动态变化【英文标题】:Form validation rules changing dynamically 【发布时间】:2019-08-11 23:14:05 【问题描述】: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 中的表单验证规则。
假设是英国:
只有电子邮件和密码是必填项。
或者如果是美国:
除了电子邮件,名字和姓氏应该是强制性的。
我是 Ajax 新手。
谁能帮帮我?
提前致谢!
【问题讨论】:
到目前为止你尝试过什么? 您可以预定义国家/地区错误信息。 【参考方案1】:试试这个答案...在验证规则而不是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>
【讨论】:
以上是关于表单验证规则动态变化的主要内容,如果未能解决你的问题,请参考以下文章