23

When I use pattern in input like this:

<input type="text" value="" pattern="(\d|(\d,\d{0,2}))"> 

I receive popup warning with text. How can I easily change this text?

John Conde
  • 217,595
  • 99
  • 455
  • 496
Torv
  • 1,214
  • 2
  • 11
  • 29

4 Answers4

43
<input type="text" value="" pattern="(\d|(\d,\d{0,2}))" title="YOUR_WARNING_TEXT" > 
voodoo417
  • 11,861
  • 3
  • 36
  • 40
12
<input type="text" value="" pattern="(\d|(\d,\d{0,2}))" oninvalid="this.setCustomValidity('ERROR_TEXT')" oninput="this.setCustomValidity('')"/>

Try this code, corrected to clear after input...

Breno
  • 121
  • 1
  • 3
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Jun 05 '17 at 13:34
  • I like that this replaces the default warning instead of appending to it – Pedro Jul 03 '17 at 19:22
  • Make sure to also add oninput to clear the setCustomValidity, otherwise the user will be stuck when they attempt to fix the error – Pedro Jul 03 '17 at 19:32
7

The text shown can be defined in the title attribute of the input tag.

kgautron
  • 7,915
  • 9
  • 39
  • 60
  • 1
    Title added to end of default warning. any way to totaly overwrite it? – Torv Jul 31 '12 at 12:18
  • Is there any reason you chose the other answer over this one even though it was answered first with the same information? I know it was a long time ago. Just curious – Dinerdo Mar 16 '17 at 22:41
5

The title is appended to the pattern warning. Just keep in mind the warnings are translated into the browser language, which can make an english string look odd.

This is the only way I found to completely replace the warning:

<input type="text" required pattern="PATTERN" oninvalid="invalid" oninput="invalid">
/**
 * Shows a custom validity message
 * @param e - event
 */
function invalid(e) {
  if (!/PATTERN/.test(e.target.value)) { // somehow validity.valid returns a wrong value
    e.target.setCustomValidity('INVALID')
  } else {
    e.target.setCustomValidity('')
  }
}

Once the form is validated, the warning keeps popping up until the value matches the pattern. If the input event is just setting setCustomValidity('') as suggested in most other answers, the default warning returns.

Fabian von Ellerts
  • 4,763
  • 40
  • 35