我已经能够在用户尚未输入电子邮件时更改错误消息,但如何在用户输入错误格式的电子邮件时更改错误消息?
这是我用Bootstrap 4风格编写的代码:
<div class="form-group">
<label>Email</label>
<input type="email" name="email" required="" class="form-control" oninvalid="this.setCustomValidity('Please Enter valid email')" oninput="setCustomValidity('')">
</div>
答案 0 :(得分:0)
以下是如何操作的示例:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
您必须更改alert
内的文字以包含您的自定义消息,并action_page.php
添加您自己的消息并添加所需的样式!
<强>更新强>
如果您不想实现自己的JavaScript功能,那么您可以继续向oninvalid
添加条件,如下所示:
<input type="email" name="email" required="" class="form-control" oninvalid="if (this.value == ''){this.setCustomValidity('This field is required!')} if (this.value != ''){this.setCustomValidity('The email you entered is invalid!')}" oninput="setCustomValidity('')">
答案 1 :(得分:0)
您只需在输入标签中添加标题即可解决此问题
<input type="email" class="form-control" name="email" id="freeform_email"
placeholder="Enter an email" required="required"
oninvalid="this.setCustomValidity('Enter an email that contains "@". Example: info@roshni.nl')" title="Email: the email contains '@'. Example: info@ros-bv.nl" />
您应该这样:
<div class="form-group">
<label>Email</label>
<input type="email" name="email" required="" class="form-control" oninvalid="this.setCustomValidity('Please Enter valid email')" oninput="this.setCustomValidity('')" title='<your text>'">
</div>
不客气。