TL; DR: Doesn't care about old browsers? Use form.reportValidity() .
Need support for older browsers? Continue reading.
In fact, you can run the scan manually.
I will use simple JavaScript in my answer to improve the reusability, jQuery is not required.
Accept the following HTML form:
<form> <input required> <button type="button">Trigger validation</button> </form>
And let's grab our user interface elements in JavaScript:
var form = document.querySelector('form') var triggerButton = document.querySelector('button')
Don't need support for legacy browsers like Internet Explorer? This is for you.
All modern browsers support the reportValidity() method for form elements.
triggerButton.onclick = function () { form.reportValidity() }
That is all we are done. Also, here is a simple CodePen using this approach.
An approach for older browsers
The following is a detailed explanation of how reportValidity() can be emulated in older browsers.
However, you do not need to copy and paste these blocks of code into your project yourself - you have ponyfill / polyfill for you.
Where reportValidity() not supported, we need to trick the browser a bit. So what will we do?
- Verify that the form is correct by calling
form.checkValidity() . This will tell us if the form is valid, but does not show the validation interface. - If the form is invalid, we create a temporary submit button and click on it. Since the form is invalid, we know that it will not actually be submitted, however it will show the user tips for verification. We will immediately remove the temporary send button so that it is never visible to the user.
- If the form is valid, we donโt need to intervene at all and let the user continue.
In code:
triggerButton.onclick = function () { // Form is invalid! if (!form.checkValidity()) { // Create the temporary button, click and remove it var tmpSubmit = document.createElement('button') form.appendChild(tmpSubmit) tmpSubmit.click() form.removeChild(tmpSubmit) } else { // Form is valid, let the user proceed or do whatever we need to } }
This code will work in almost all common browsers (I successfully tested it before IE11).
Here is a working example of CodePen.