简体   繁体   English

如何触发 HTML5 验证并在更改事件上设置自定义消息?

[英]How to trigger HTML5 validation and set custom message on change event?

I have input text field that should allow only numeric values 0-9 and should be exactly eight digits long.我有输入文本字段,它应该只允许数字值0-9并且长度应该正好是八位数字。 This should be controlled by the onChange event.这应该由onChange事件控制。 Once user is done typing validation should be triggered.用户完成输入验证后,应触发。 If value is correct Ajax request will reach out to the server, if not user should see the message like other messages in HTML 5 validation.如果值正确,Ajax 请求将到达服务器,否则用户应该像 HTML 5 验证中的其他消息一样看到该消息。 Here is example of my code:这是我的代码示例:

 $('#userid').on('change', checkUser); function checkUser(e) { var fldObj = $(this); if (!e.target.checkValidity()) { fldObj[0].setCustomValidity('Invalid User ID.'); console.log(fldObj.val()); } else { //send ajax request console.log('User ID is valid!'); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="userid" id="userid" value="" pattern="[0-9]{8}" placeholder="Enter User ID">

My code is not working correct.我的代码工作不正常。 I do not see the message if I enter invalid value.如果输入无效值,我将看不到该消息。 If anyone knows the reason why the message is not displaying please let me know.如果有人知道消息未显示的原因,请告诉我。

Validity is only reported when the input is part of a form.仅当输入是表单的一部分时才报告有效性。 Try entering an invalid value and submitting the form in the snippet below.尝试输入无效值并在下面的代码段中提交表单。

 $('#userid').on('change', checkUser); function checkUser(e) { var fldObj = $(this); if (!e.target.checkValidity()) { fldObj[0].setCustomValidity('Invalid User ID.'); fldObj[0].parentElement.reportValidity(); console.log(fldObj.val()); } else { //send ajax request console.log('User ID is valid!'); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <input type="text" name="userid" id="userid" value="" pattern="[0-9]{8}" placeholder="Enter User ID"> <button type="submit">Submit</button> </form>

If you don't want to wait for the submit button to be clicked, check out HTMLFormElement.reportValidity() .如果您不想等待提交按钮被点击,请查看HTMLFormElement.reportValidity()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM