JordyvD
JordyvD

Reputation: 1615

Get default message for required validation

I'd like to show the default error message for validation (e.g. required) with JavaScript.

The default message provided by the browser is fine (and it translates it automatically), I just want to trigger it programmatically with custom validation.

Is it possible to get the default error message provided by the browser?

Upvotes: 3

Views: 2613

Answers (1)

Tristan De Oliveira
Tristan De Oliveira

Reputation: 808

This should work

input.addEventListener('change', function(e) {
    if (// your check)
        this.setCustomValidity('Error');
    else
        this.setCustomValidity('');
});

so when you submit the form the custom validity message will be show by the browser

EDIT:

Example on 'stackoverflow'

document.querySelector('#search > div > input').setCustomValidity('Hello')

if your click on search button you will have

enter image description here

To get the validation message of the browser you can do this:

document.querySelector('#search > div > input').validationMessage

Upvotes: 2

Related Questions