且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

HTML5,如何在值更改时强制输入模式验证?

更新时间:2023-02-12 10:52:43

免责声明:
我在这里要说的全部适用于所有现代浏览器.在此上下文中,术语现代浏览器"不包括IE9和更早版本.Safari Windows版也仅部分支持.

Disclaimer:
All I am about to say here works for all modern browsers. The term "modern browser" in this context excludes IE9 and earlier. Also Safari for Windows has only partial support.

如果您只需要样式指示器,则可以为此使用纯CSS:

If all you need is a styling indicator, you can use pure CSS for this:

input[pattern]:invalid{
  color:red;
}

使用模式时,浏览器会自动完成 onsubmit 验证(不适用于Windows的Safari).

When using pattern, the onsubmit validation is automatically done by the browser (does not work in Safari for Windows).