Html 在输入中使用模式时如何更改警告文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11739079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:58:53  来源:igfitidea点击:

How to change warning text when pattern is used in input?

html

提问by Torv

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?

我收到带有文本的弹出警告。如何轻松更改此文本?

回答by voodoo417

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

回答by kgautron

The text shown can be defined in the titleattribute of the inputtag.

显示的文本可以titleinput标签的属性中定义。

回答by TJH

This question has already been answered in the past. Please see the following URL for the answer: HTML5 form required attribute. Set custom validation message?

这个问题在过去已经得到了回答。请参阅以下 URL 以获取答案:HTML5 表单必需属性。设置自定义验证消息?

回答by Breno

<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...

试试这个代码,输入后更正以清除......

回答by Fabian von Ellerts

The titleis 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.

title被附加到图案警告。请记住,警告被翻译成浏览器语言,这会使英文字符串看起来很奇怪。

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 inputevent is just setting setCustomValidity('')as suggested in most other answers, the default warning returns.

一旦表单被验证,警告就会不断弹出,直到值与模式匹配。如果input事件只是setCustomValidity('')按照大多数其他答案中的建议设置,则返回默认警告。