我正在使用jQuery验证插件来验证网站上的表单。它在需要一定数量的字符或特定格式(例如电子邮件(的字段上可以正常工作,但是如果某人聚集了所需的输入,然后将其放在不输入的情况下,则不会立即显示错误。我想做的是,如果某人聚焦了所需的输入,然后将其转移到另一个字段(模糊(而无需输入任何内容,它将立即显示错误。这可能吗?
$(function() {
$('#contact').validate({
rules: {
fname: 'required',
email: {
required: true,
email: true
}
},
messages: {
fname: 'Please enter your first name',
msgemail: 'Please enter a valid email address'
}
});
});
input {
display:block;
margin-top:20px;
}
label.error {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="contact">
<input type="text" name="fname" placeholder="First name" /> <!-- This should show error if left empty on blur -->
<input type="text" name="email" placeholder="Email" />
</form>
调用构造函数时添加onfocusout
事件。
$(function() {
$('#contact').validate({
onfocusout: function(element) {
$(element).valid();
},
rules: {
fname: 'required',
email: {
required: true,
email: true
}
},
messages: {
fname: 'Please enter your first name',
msgemail: 'Please enter a valid email address'
}
});
});
input {
display:block;
margin-top:20px;
}
label.error {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="contact">
<input type="text" name="fname" placeholder="First name" /> <!-- This should show error if left empty on blur -->
<input type="text" name="email" placeholder="Email" />
</form>