可以html5表单验证吗
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
没有表格可以吗
<div>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</div>
Run Code Online (Sandbox Code Playgroud)
小智 5
是的,使用约束验证 API。请参阅http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api。例如,您可以调用element . checkValidity(). 另请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation或https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/检查有效性。例如:
var email = document.getElementById('email');
var valid = email . checkValidity();
if (!valid) ...
Run Code Online (Sandbox Code Playgroud)
或使用失败invalid时触发的事件checkValidity():
email.addEventListener("invalid", function() { alert("Email invalid"); });
Run Code Online (Sandbox Code Playgroud)
您可以使用setCustomValidity设置有效性状态和/或错误消息:
if (!email.value) email.setCustomValidity("Email is missing");
Run Code Online (Sandbox Code Playgroud)