正如大多数人所说,您必须使用input.setCustomValidity("message")
.
这里的问题是您无法在submit
事件中检查该验证,因为您需要进行 ajax 调用然后setCustomValidity
异步设置。
所以基本上你必须使用change
输入字段的事件并对每次更改进行 ajax 调用。或者删除提交按钮并使用click
普通按钮的事件,检查ajax调用中的唯一电子邮件,然后通过javascript调用提交。
查看使用 jQuery 的最后一个选项的示例:
<form action="/sign-in" id="form">
<input type="email" id="email" required/>
<button id="submit">Submit</button>
</form>
// we capture the click instead the submit
$("#submit").on("click",function(){
var $elem = $("#email");
var email = $elem.val();
//the ajax call returns true if the email exists
$.get( "ajax/checkUniqueEmail", function(data) {
if(data === "true"){
$elem.setCustomValidity("This email already exists.");
}else{
$elem.setCustomValidity("")
}
//then we submit the form
$("#form").submit();
});
});