1

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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think OP was asking how to have the error appear onchange.
The part below the snippet should cover that.
It seems that if the field is invalid once, it never goes back valid...Does it happen also to you? It seems it depends from setCustomValidity() method. How to fix that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.