DEV Community

Reishi Mitani
Reishi Mitani

Posted on

Modifying Input Error Messages with jQuery

I recently needed a way to change the language and the content of the error messages in my web app using jQuery.

Suppose an image is required to upload in a form.
The default message would be like the one below, Please select a file.

Alt Text

However, you might not like the content of the message or the language of the message. Add the following jQuery code to your file.

Make sure to change the id of the file (which in this case is myform) to your own form id.

$('#myform input[type=file]').on('change invalid', function() {
    var textfield = $(this).get(0);

    // 'setCustomValidity not only sets the message, but also marks
    // the field as invalid. In order to see whether the field really is
    // invalid, we have to remove the message first
    textfield.setCustomValidity('');

    if (!textfield.validity.valid) {
        textfield.setCustomValidity('画像は添付してね! At least one image is required for this form!');  
    }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)