简体   繁体   中英

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. This should be controlled by the onChange event. 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. 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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