我是HTML5和JS的新手,遇到了这个麻烦:
我在点击提交按钮后尝试显示自定义验证消息。它工作正常,例如,如果名称字段为空,它将在按下按钮后显示我的自定义消息。但是,按下按钮后,当我填满字段时,消息会一直弹出。
这也只发生在我当前的领域。例如,如果我在页面上的其他位置单击鼠标然后返回该字段,则消息将停止弹出
尝试运行以下代码段,希望您能理解这个问题。
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>WORKING WITH FORMS IN HTML5</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.h5validate.js"></script>
<style>
@charset "UTF-8";
input:required+label:AFTER {
content: "*";
color: red
}
input:focus:invalid {
background-color: pink;
}
input:focus:valid {
background-color: #E5FFCC;
}
input:valid {
border-color: green;
}
input:invalid {
border-color: red;
}
input:optional {
border-color: silver;
}
input:focus:optional {
background-color: transparent;
}
#subb {
border-radius: 25px;
width: 200px;
height: 50px;
background-image: linear-gradient(to right, black 0%, white 100%);
color: black;
opacity: 0.8;
}
[data-Required] {
color: blue;
font-size: 20px;
}
</style>
<!--
<script>
function test(){
var elements = document.getElementsByTagName("INPUT");
for(var i = 0 ; i < elements.length; i++){
if(elements[i].validity.valueMissing){
elements[i].setCustomValidity("Dont leave me hanging :(");
}
else if(elements[i].validity.patternMismatch){
elements[i].setCustomValidity("Follow the pattern my friend");
}
else if(elements[i].validity.typeMismatch){
elements[i].setCustomValidity("Wrong type!!!");
}
else{
elements[i].setCustomValidity("");
}
}
}
</script>
-->
<script>
$(document).ready(function() {
var elements = $("input");
for (var i = 0; i < elements.length; i++) {
if (elements[i].validity.valueMissing) {
elements[i].setCustomValidity("Dont leave me hanging :(");
} else if (elements[i].validity.patternMismatch) {
elements[i].setCustomValidity("Follow the pattern my friend");
} else if (elements[i].validity.typeMismatch) {
elements[i].setCustomValidity("Wrong type!!!");
} else {
elements[i].setCustomValidity("");
}
}
$('#myform').Submit();
});
</script>
</head>
<body>
<form id="myform">
<input data-Required class="error" type="text" required id="name" placeholder="John Doe">
<label for="name">Full Name</label>
<br>
<br>
<input data-Required type="email" required id="email" placeholder="johhndoe@xyz.com">
<label for="email">Email</label>
<br>
<br>
<input data-Required type="phone" required id="phonenumber" pattern="\d\d\d\d\-\d\d\d\d\d\d\d" placeholder="0300-0000000">
<label for="phonenumber">Mobile Phone Number</label>
<br>
<br>
<input type="text" id="address" placeholder="houseno,streetno,societyname,cityname">
<label for="address">Address</label>
<br>
<br>
<input type="button" value="Submit" id="subb">
</form>
</body>
</html>
&#13;
答案 0 :(得分:1)
首先,为了更好地控制您的验证,您应该使用<input type="button" value="Submit" id="subb">
而不是submit
类型,并为您的表单添加一个ID formId
。最后,在您的所有验证都被清除后,您可以提交以下表格,
$('#formId').submit();
答案 1 :(得分:0)
验证消息的弹出是由于浏览器提供的html5默认验证功能。
我可以看到你使用了h5validate.js插件
使用此功能,您可以停止默认验证并编写自己的自定义验证消息。
$('#frm').h5Validate({
errorClass:'black'
});
看看它是否对你有所帮助:)。