Customize the browser message for a "required" field

Asked

Viewed 19,566 times

10

With the attribute required (English), for example in a field of the text, the browser will present a balloon to the user to realize that this field is required and must be filled.

The problem begins with the message itself that being generic does not help the user. On the other hand, the message concerns the language of the browser and not exactly the language of the application.

Example in Jsfiddle

<form>
    <input type="text" required>
    <button type="submit">Enviar</button>
</form>

By clicking "Send" without filling in the field, I will receive the message in Firefox:

Please Fill out this field.

Question

How we can customize the message that the browser presents to a input with the attribute required ?

3 answers

11


You can use HTML for this with the title tag:

title="This field should not be left blank."

If it doesn’t work with Firefox you can add:

x-moz-errormessage="This field should not be left blank."

You could also do by Jquery:

$(document).ready(function() {
    var elements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("This field cannot be left blank");
            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})

Short answer translated from here: https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message

  • The title no longer works on Chrome, the response you based on has been updated.

4

Or, in Html5, simplifying "a little" the solution, follows:

<div class="controls">
  <input class="span4" type="text" name="Campo" placeholder="Campo"  value=""  required oninvalid="this.setCustomValidity(\'Campo requerido\')">
</div>

4

You cannot have the ' ' bar inside the message. In addition, we also need to delete the message as soon as the user makes some correction in the field, so we use the event onchage:

Then the correct and the complete line would look like this:

<div class="controls">
<input class="span4" type="text" name="Campo" placeholder="Campo"  value=""  
required oninvalid="this.setCustomValidity('Campo requerido')" 
onchange="try{setCustomValidity('')}catch(e){}">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.