How to implement the native verification boxes in HTML5, such as required, pattern, etc., when the verification is invalid? Why does a prompt box with different content pop up when it is invalid because different constraints are not met? Is it implemented by combining the invalid event and the validity attribute? How does the setCustomValidity() method work? I feel like this content is getting more confusing the more I read it, so I would like to ask some experts for advice...
歡迎選擇我的課程,讓我們一起見證您的進步~~
Go check out the form verification on MDN. I think it’s quite clear. You can follow the small demo and you’ll understand it slowly.
required: Blank verification, for example:
<form>
<input type="text" required oninvalid="setCustomValidity('此處不能為空!')" oninput=('setCustomValidity()')>
<input type="submit" value="提交">
</form>
If the value of input[type=text] is empty, a prompt box will pop up and form submission will be prevented;
pattern: matches a regular expression, for example:
<form>
<input type="text" pattern="[0-9]{3}" oninvalid="setCustomValidity('請輸入3個數(shù)字!')" oninput=('setCustomValidity()')>
<input type="submit" value="提交">
</form>
If the value of input[type=text] is not 3 digits, a prompt will be raised when clicking the submit button