Customize the browser message to a "required"

8

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

The problem starts with the message itself being generic does not help the user. On the other hand, the message refers to the language of the browser and not the language of the application itself.

Example in JSFiddle

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

When I click on "Send" without filling in the field, in Firefox in English I will get the message:

  

Please fill out this field.

Question

How can we customize the message that the browser displays for a input with the required attribute?

    
asked by anonymous 06.03.2014 / 17:31

3 answers

9

You can use HTML for this with the title tag:

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

If it does not work with Firefox you can add:

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

You could also do it 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("");
        };
    }
})

Briefly and translated from here: link

    
06.03.2014 / 17:34
5

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>
    
06.03.2014 / 17:37
0

You can not 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, then we use the onchage event:

Then the correct and 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>
    
03.09.2018 / 21:36