Search code examples
javascripthtmlconstraint-validation-api

HTML5 constraint validation for custom check


I would like to check if username and email address is unique on client side.

Is there any way to add custom validation for constraint validation?

Or is there any other recommended way for this?

I assume I have to send async http request (I am using node js on server side) but would like to follow best practice for this one.


Solution

  • Yes you can use the setCustomValidity function from the constraint validation api, which is part of every form field (e.g., HTMLInputElement).

    <input name="username">
    <script>
      const field = document.querySelector('[name="username"]');
      field.addEventListener('change', () => {
        fetch('https://example.com/myapiforcheckingusername' {
          method:'POST',
          body: JSON.stringify({username: field.value})
        }).then((response) => {
          const alreadyExists = // process response to check if username already exists
    
          if (alreadyExists) {
            field.setCustomValidity('The username already exists!');
          }
        });
      });
    </script>
    

    The above code shows how to make an async validation on an input field. If the setCustomValidity is not the empty string it means it is a form error. If checkValidity is called on the accompanying form it returns false then.

    You can check the MDN documentation for further examples on this matter.