3

I need to know, How can I change the default text for each html validation to a custom error message.

I read this article: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

And this is my html code:

<form>
  <input id="choose" name="i_like" required>
  <button>Submit</button>
</form>

And the message is :

Please fill out this field.

The question is , I want to change this default error message.

EDITED:

And also I want to define a fixed message and change a part of this message as custom error message for validation, at this time this is my second problem.

e.g:

"Please enter [----] before send"

Thank you for your helping.

  • 1
    Possible duplicate of [HTML5 form required attribute. Set custom validation message?](https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message) – Bhargav Chudasama Oct 31 '18 at 08:02

1 Answers1

3

You can use setCustomValidity method to define your own custom error message. And about your second issue, you should define a function, and set name attribute for passing keyword to your fixed message.

Declare a Javascript function:

<script>

    function applyValidation(x){

        var msg = "Please enter"+ x.name +" before send"
        x.setCustomValidity(msg);
    }
</script>

Then Use it in your html:

<form>
    <input type="text" id="choose" name="input-name1" 
    required oninvalid="applyValidation(this)"
    oninput="setCustomValidity('')"  />

    <input type="text" id="choose" name="input-name2" 
    required oninvalid="applyValidation(this)"
    oninput="setCustomValidity('')"  />

  <button>Submit</button>
</form>
Siavash
  • 2,813
  • 4
  • 29
  • 42