如何启用/禁用HTML5必需的字段验证



我有一个表单,需要对3个字段进行条件验证。这些字段是电子邮件、名字和姓氏。所以电子邮件字段文本框有价值,我不需要验证FirstName&姓氏,我的意思是后面的2可以是空的。如果FirstName&LastName字段有值,电子邮件可以为空。

我正在使用HTML5必需的属性。

如何使用jQuery启用禁用HTML5所需的验证器?

删除

$("#txt").removeAttr("required");

添加

$("#txt").attr("required","");

检查值并删除required属性。

$('#btnSubmit').on('click', function() {
if ($('input[name=last]').val() != "" && $('input[name=first]').val() != "")
$('input[name=Email]').removeAttr("required");
else if ($('input[name=Email]').val() != "") $('input[name=first],input[name=last]').removeAttr("required");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
First:
<input type="text" name="first" value="" required />
<br />Last:
<input type="text" name="last" value="" required />
<br />Email:
<input type="text" name="Email" value="" required />
<br />
<input type="submit" value="Submit" id="btnSubmit" />
</form>

试试这个:

jQuery

$('#Email').removeAttr('required');​​​​​

这可能有助于

$('button').click(function(){
$('input').each(function(){
$(this).prop('required', !$(this).attr('required'))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" nam="FirstName" placeholder="First Name" required/>
<input type="text" nam="LastName" placeholder="Last Name" required/>
<input type="text" nam="Email" placeholder="Email" required/>
<br/>
<button>
Enable/Disable All inputs
</button>

这就像togglingrequired attribute

最新更新