espresso_coffee
espresso_coffee

Reputation: 6110

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.

Upvotes: 1

Views: 2919

Answers (1)

crenshaw-dev
crenshaw-dev

Reputation: 8412

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().

Upvotes: 1

Related Questions