75

I am trying to change the language of the error message in the html5 form field.

I have this code:

<input type="text" name="company_name"  oninvalid="setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required /> 

but on submit, even the field is not blank, I still get the error message.

I tried with <input type="text" name="company_name" setCustomValidity('Lütfen işaretli yerleri doldurunuz') required />

but then the english message is displayed. Anyone know how can I display the error message on other language?

Regards,Zoran

Zoran
  • 1,321
  • 4
  • 22
  • 41

12 Answers12

99

setCustomValidity's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.

You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.

The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message.

<input type="text" required title="Lütfen işaretli yerleri doldurunuz" />

enter image description here

If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.

janfoeh
  • 10,243
  • 2
  • 31
  • 56
  • I will go with javacript solution. any easy way to check for all empty fields? in my case all fields are required, and form is quite long..how can the javascript be rewritted, so it will check for all fields? or it must be one by one? – Zoran May 25 '12 at 13:05
  • 3
    the code with the title work only with custom css i guess or only in some browser. I add that and I can't see the turkish message – Zoran May 25 '12 at 13:13
  • I have added an [updated version](http://jsfiddle.net/zpkKv/3/) that should check all inputs, textareas and select fields. Which browser are you testing in? HTML5 form validation is not supported across the board. – janfoeh May 25 '12 at 14:38
  • Just a suggestion for the fiddle, alter the selector 'change invalid' to 'change' such that the error disappears when the rule is fulfilled. – Bogdan M. Jan 17 '18 at 13:10
  • 2
    Even fiddle doesn't work with adding 'title' to input – Vinita Rathore Jun 29 '18 at 06:37
  • 10
    The title attribute no longer works. It's not working on Chrome or Firefox in 2018 – Ahmad Alfy Aug 14 '18 at 15:36
58

your forget this in oninvalid, change your code with this:

    oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')"

enter image description here

<form><input type="text" name="company_name"  oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required /><input type="submit">
</form>
javad shariaty
  • 939
  • 10
  • 14
16

HTML:

<form id="myform">
    <input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  type="email" required="required" />
    <input type="submit" />
</form>

JAVASCRIPT :

function InvalidMsg(textbox) {
    if (textbox.value == '') {
        textbox.setCustomValidity('Lütfen işaretli yerleri doldurunuz');
    }
    else if (textbox.validity.typeMismatch){
        textbox.setCustomValidity('Lütfen işaretli yere geçerli bir email adresi yazınız.');
    }
    else {
       textbox.setCustomValidity('');
    }
    return true;
}

Demo :

http://jsfiddle.net/patelriki13/Sqq8e/4

Atduyar
  • 77
  • 1
  • 9
Rikin Patel
  • 8,848
  • 7
  • 70
  • 78
13

This work for me.

<input oninvalid="this.setCustomValidity('custom text on invalid')" onchange="this.setCustomValidity('')" required>

onchange is a must!

dimitar
  • 1,019
  • 13
  • 19
7

I know this is an old post but i want to share my experience.

HTML:

<input type="text" placeholder="Username or E-Mail" required data-required-message="E-Mail or Username is Required!">

Javascript (jQuery):

$('input[required]').on('invalid', function() {
    this.setCustomValidity($(this).data("required-message"));
});

This is a very simple sample. I hope this can help to anyone.

Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
6

TLDR: Usually, you don't need to change the validation message but if you do use this:

<input
    oninvalid="this.setCustomValidity('Your custom message / 您的自定义信息')"
    oninput="this.setCustomValidity('')"
    required="required"
    type="text"
    name="text"
>

The validation messages are coming from your browser and if your browser is in English the message will be in English, if the browser is in French the message will be in French and so on.

If you an input for which the default validation messages doesn't work for you, the easiest solution is to provide your custom message to setCustomValidity as a parameter.

...
oninvalid="this.setCustomValidity('Your custom message / 您的自定义信息')"
...

This is a native input's method which overwrites the default message. But now we have one problem, once the validation is triggered, the message will keep showing while the user is typing. So to stop the message from showing you can set the validity message to empty string using the oninput attribute.

...
oninput="this.setCustomValidity('')"
...
Nedko Dimitrov
  • 4,350
  • 3
  • 28
  • 30
  • 1
    Both @dimitar 's solution and this are working for me (Brave browser), but I prefer this solution because onchange event on form elements _fires when_ the element loses focus, not immediately after the modification (per http://rakshasingh.weebly.com/blog/what-is-the-difference-between-oninput-and-onchange-events-in-javascript). – sianipard Jan 19 '21 at 04:24
  • 1
    This helped me.. Nothing else didn't work.. THANK YOU :) –  Aug 09 '22 at 09:16
3
//Dynamic custome validation on all fields
//add validate-msg attr to all inputs
//add this js code

$("form :input").each(function(){
                    var input = $(this);
                    var msg   = input.attr('validate-msg');
                    input.on('change invalid input', function(){
                        input[0].setCustomValidity('');
                        if(!(input[0].validity.tooLong || input[0].validity.tooShort)){
                            if (! input[0].validity.valid) {
                                input[0].setCustomValidity(msg);
                            }
                        }


                    });
                });
1
<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />

this can help you even more better, Fast, Convenient & Easiest.

1

For the lost souls who are seeking a way to fully localize their error messages, see the snippet below. In short, you have to switch over the properties of event.target.validity and override the corresponding error message using event.target.setCustomValidity(message). If you just care about the empty field case as OP, just consider the case of valueMissing.

Note that the handler is passed in the React way, but other answers already covered how to do it in vanilla JS.

For the meaning of each validity state and how to implement customized error messages, see MDN: Validating forms using JavaScript.

const handleInvalidForm = (event) => {
    const { patternMismatch,
        tooLong,
        tooShort,
        rangeOverflow,
        rangeUnderflow,
        typeMismatch,
        valid,
        valueMissing } = event.target.validity;

    if (patternMismatch) 
        event.target.setCustomValidity('...');
    else if (tooLong)
        event.target.setCustomValidity('...');
    else if (tooShort)
        event.target.setCustomValidity('...');
    else if (rangeOverflow)
        event.target.setCustomValidity('...');
    else if (rangeUnderflow)
        event.target.setCustomValidity('...');
    else if (typeMismatch)
        event.target.setCustomValidity('...');
    else if (valid)
        event.target.setCustomValidity('...');
    else if (valueMissing)
        event.target.setCustomValidity('...');
}

// ...

<form onSubmit={handleFormSubmit}
      onInvalid={handleInvalidForm}
>
    {emailTextField}
    {passwordTextField}
    {signInButton}
</form>

Firmin Martin
  • 280
  • 3
  • 15
0
<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Please Enter your first name')" >

this can help you even more better, Fast, Convenient & Easiest.

Shashank Malviya
  • 670
  • 6
  • 17
  • You would have to use `setInterval` to set the validity string to `""` after for example 1000 ms. Else the input element remains "invalid". – malthe Feb 26 '19 at 15:11
  • @malthe **setinterval** will do the samething again and again and also we have to remove the interval once its done. – Shashank Malviya Mar 30 '19 at 02:41
0

Do it using JS. Grab the class of the error message, and change it's content for whereever it appears.

var myClasses = document.getElementsByClassName("wpcf7-not-valid-tip");

for (var i = 0; i < myClasses.length; i++) {
    myClasses[i].innerHTML = "Bitte füllen Sie das Pflichtfeld aus.";
}
Ron16
  • 445
  • 6
  • 11
0

<form>
  <input
    type="text"
    name="company_name"
    oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')"
    required
  /><input type="submit" />
</form>
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
PeeGee
  • 1