我有以下呈现形式:
<div class="form-row clearfix">
<label for="FirstName" class="overlay">First name</label>
<input id="FirstName" class="input-validation-error textbox" type="text" placeholder="Required" value="" name="FirstName" data-val-required="Enter first name" data-val-length-min="2" data-val-length-max="50" data-val-length="Enter 2 to 50 characters" data-val="true" />
<div class="validate-error field-validation-error" data-valmsg-replace="true" data-valmsg-for="FirstName"></div>
</div>
<div class="form-row clearfix">
<label for="Surname" class="overlay">Surname</label>
<input id="Surname" class="input-validation-error textbox" type="text" placeholder="Required" value="" name="Surname" data-val-required="Enter surname" data-val-length-min="2" data-val-length-max="50" data-val-length="Enter 2 to 50 characters" data-val="true" />
<div class="validate-error field-validation-error" data-valmsg-replace="true" data-valmsg-for="Surname"></div>
</div>
<div class="form-row clearfix">
<label for="TelNo" class="overlay">Tel no.</label>
<input id="TelNo" class="input-validation-error textbox" type="text" placeholder="Optional" value="" name="TelNo" />
<div class="validate-error field-validation-error" data-valmsg-replace="true" data-valmsg-for="TelNo"></div>
</div>
<div id="postcode-holder" class="form-row clearfix">
<label for="Postcode" class="overlay">Postcode</label>
<input id="Postcode" class="input-validation-error textbox" type="text" placeholder="Required" value="" name="Postcode" data-val-required="Enter postcode" data-val-length-min="2" data-val-length-max="10" data-val-length="Enter 2 to 10 characters" data-val="true" />
<div class="validate-error field-validation-error" data-valmsg-replace="true" data-valmsg-for="Postcode"></div>
<input id="find-addresses" name="find-addresses" type="submit" class="orange-button" value="Find Address" />
</div>
<div class="button-holder">
<button name="order-brochure" class="large orange-button">Order Brochure<span class="sprite large-white-arrow"></span></button>
</div>
你可以看到哪两个按钮:
find-addresses
- 这将用于邮政编码查找
order-brochure
- 用于提交表单数据
我正在尝试使用find-addresses按钮来验证表单中是否输入了邮政编码,但是当我按下按钮时,它会验证所有字段。
我尝试添加类取消 - 但是这会取消所有验证,所以我尝试了以下内容:
$("#find-addresses").on("click", function () {
//#request-brochure-form is the correct id for the form
$("#request-brochure-form").validate({
rules: {
Postcode: "required",
Surname: {
required: false
}
}
});
});
但这似乎没有改变任何东西。如何取消查找地址按钮上所有必填字段(除邮政编码字段外)的验证?
答案 0 :(得分:1)
发生点击事件时,即时应用/附加规则。
$('#find-addresses').on('click', function(){
$('[name="Postcode"]').rules('add', {
required: true,
email: true
});
$('#Other_Form_Fields').rules('remove');
$('#request-brochure-form').valid(); // trigger the validation & do NOT submit
});
当您使用其他按钮时,在使用Click事件时,请移除#find-address
点击时应用的规则。
有关详细信息,请参阅This。
如果您想使用其他按钮进行设置,如果您想要使Surname
无效,请使用$('[name="Surname"]').rules('remove');