2

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
BK C.
  • 573
  • 2
  • 7
  • 16
  • Canonical link if you are using Selenium: https://stackoverflow.com/questions/55223934/how-to-handle-html-constraint-validation-pop-up-using-selenium – TylerH Nov 23 '22 at 14:21

2 Answers2

0

you can make a request on input's blur to check if what user has written in input is unique or not and show result to user with check mark or red X or you can show user after he clicked on signup button but i prefer the first solution

0

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.

Stefan
  • 1,151
  • 1
  • 8
  • 13