为什么所有的验证都发生在同一时间
这是jquery脚本。验证工作,但是,如果您将一个字段留空,然后单击字段到表单上,则所有验证消息都会显示在表单中的每个字段中,而不仅仅是空的字段。以及如何以我的示例中的格式验证jQuery中的电子邮件地址?任何任何想法?感谢您的帮助提前为什么所有的验证都发生在同一时间
$(document).ready(function() {
$('#firstname').on('blur', function() {
if ($('#firstname').val() == '') {
$('.errorMsg').show();
} else {
$('.errorMsg').hide();
}
});
$('#lastname').on('blur', function() {
if ($('#lastname').val() == '') {
$('.errorMsg').show();
} else {
$('.errorMsg').hide();
}
});
$('#email').on('blur', function() {
if ($('#email').val() == '') {
$('.errorMsg').show();
} else {
$('.errorMsg').hide();
}
});
$('#roomtype').on('blur', function() {
if ($('#roomtype').val() == '') {
$('.errorMsg').show();
} else {
$('.errorMsg').hide();
}
});
});
,因为你正在使用$('.errorMsg').show();
将针对所有班级,名字= errorMsg
。
确保每个验证只针对特有的错误消息
使用$(this).next(".errorMsg").show();
和$(this).next(".errorMsg").hide();
每个输入
例如:
if ($('#email').val() == '') {
$(this).next(".errorMsg").show();
} else {
$(this).next(".errorMsg").hide();
}
电子邮件验证实例:
$('.errorMsg').hide();
$('#email').on('blur', function(event) {
if (event.target.checkValidity()){
$(this).next('.errorMsg').hide();
} else {
$(this).next('.errorMsg').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input id="email" type="email" placeholder="your email">
<span class="errorMsg">Not Valid!!!!!!!!!!!</span>
</form>
这工作改变了,谢谢你。你知道我可以如何为电子邮件地址添加适当的验证,以便它需要采用正确的格式吗? – Smith
@Smith不要关闭输入标签,有禁止关闭的标签:'img,input,br,hr,meta'等。 –
@Smith'' –
什么是您的html? –
\t 名字需要 \t 在形式,这是什么名字,姓氏,电子邮件和roomtype一切的样子,只是id和标签相应 – Smith