Search code examples
javascripthtmlforms

How to use HTML form.checkValidity()?


Reading a website's source code that uses MVC, I struggled trying to understand some of it.

Code snippet of the view:

function submitForm (action) {
  var forms = document.getElementById('form')
  forms.action = action
  if (forms.checkValidity()) {
    forms.submit()
  } else {
    alert('There is still an empty field')
  }
}

I want to execute some code if the form is missing certain inputs.


Solution

  • checkValidity() is a HTML5 method and

    When the checkValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must fire a simple event named invalid that is cancelable (but in this case has no default action) at the element and return false. Otherwise, it must only return true without doing anything else.

    Please learn more about how to use form validation constraints here. There are number of useful methods you can use, customize and even build custom validation methods.

    You also can find basic explanation and examples in w3schools. Hope this helps.