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

Dan*_*iel 14 validation html5

我正在尝试学习HTML5并遇到以下问题.我想使用patterninput关键字在用户输入时验证输入(例如,在按Tab键或从输入框更改焦点后进行验证).

我尝试过以下方法:

<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" onchange="this.variable.validate()" />  </li>
Run Code Online (Sandbox Code Playgroud)

还有:

<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" />  </li>
Run Code Online (Sandbox Code Playgroud)

我编写了代码

onchange="this.variable.validate()" 
Run Code Online (Sandbox Code Playgroud)

如何触发价值变化验证?我只能这样做onSubmit.

awe*_*awe 9

免责声明:
我在这里说的所有内容适用于所有现代浏览器.在此上下文中,术语"现代浏览器"排除了IE9及更早版本.此外,Safari for Windows仅提供部分支持.

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

input[pattern]:invalid{
  color:red;
}
Run Code Online (Sandbox Code Playgroud)

使用模式时,onsubmit验证由浏览器自动完成(在Safari for Windows中不起作用).

  • OP 请求验证**值更改**,而不是*提交*。 (3认同)

小智 6

使用reportValidity()

$('#test').on('input',function (e) {  
    e.target.setCustomValidity('')
if ($(this).val()>3) {
    console.log('o~~~~error');
    this.setCustomValidity('123')
    // this.checkValidity()
   this.reportValidity();
}
Run Code Online (Sandbox Code Playgroud)

然后,当#test输入大于3时,提示自动弹出

$('#test').on('input',function (e) {  
    e.target.setCustomValidity('')
if ($(this).val()>3) {
    console.log('o~~~~error');
    this.setCustomValidity('123')
    // this.checkValidity()
   this.reportValidity();
}
Run Code Online (Sandbox Code Playgroud)
   $('#test').on('input', function(e) {
   this.setCustomValidity('')
     if ($(this).val() > 3) {
       this.setCustomValidity('wooo~~~~')
     }
     // e.target.checkValidity()
     this.reportValidity();
   })
Run Code Online (Sandbox Code Playgroud)

https://html.spec.whatwg.org/#dom-cva-reportvalidity


Ale*_*lex 5

<input type="text" name="country" pattern="[A-z]{3}" oninput="this.reportValidity()" />
Run Code Online (Sandbox Code Playgroud)

检查oninput位。

您可能想要检查旧版浏览器,例如:

<input type="text" name="country" pattern="[A-z]{3}"
    oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}"/>
Run Code Online (Sandbox Code Playgroud)


kyl*_*lex 0

您看过 javascript 的“onkey”函数吗?

onkeyup如果您在用户输入时想要某些东西,则可能是您正在寻找的。

此外,onchange当字段失去焦点时会发生,而当onkeyup用户键入时会触发。取决于你需要哪个。

你们很多人想尝试这样的事情:

onchange = variable.validate(this.value)