Html HTML5,如何在值更改时强制输入模式验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6456149/
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
HTML5, how to force input pattern validation on value change?
提问by Daniel
I am trying to learn HTML5 and came across the following. I would like to use the pattern
input keyword to validate the input as the user types it (e.g. validation after pressing tab or changing focus from input box).
我正在尝试学习 HTML5 并遇到以下问题。我想pattern
在用户键入时使用input 关键字来验证输入(例如,在按 Tab 键或从输入框中更改焦点后进行验证)。
I have tried the following:
我尝试了以下方法:
<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" onchange="this.variable.validate()" /> </li>
And as well:
还有:
<input name="variable" value="" tabindex="1" maxlength="13" required="required" pattern="${expectedValue}" /> </li>
I made up the code for
我编写了代码
onchange="this.variable.validate()"
How to trigger the validation on value change? I am able to do this only onSubmit
.
如何触发对值更改的验证?我只能做到这一点onSubmit
。
回答by awe
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 Windowshas only partial support.
免责声明:
我在这里要说的所有内容都适用于所有现代浏览器。在此上下文中,术语“现代浏览器”不包括 IE9 及更早版本。此外,Windows 版Safari仅提供部分支持。
If all you need is a styling indicator, you can use pure CSS for this:
如果你只需要一个样式指示器,你可以使用纯 CSS:
input[pattern]:invalid{
color:red;
}
When using pattern, the onsubmit
validation is automatically done by the browser (does not work in Safari for Windows).
使用模式时,onsubmit
验证由浏览器自动完成(不适用于 Windows 的 Safari)。
回答by xxhgnxx
Use reportValidity()
使用reportValidity()
$('#test').on('input',function (e) {
e.target.setCustomValidity('')
if ($(this).val()>3) {
console.log('o~~~~error');
this.setCustomValidity('123')
// this.checkValidity()
this.reportValidity();
}
then when the #test input is bigger than 3 there is a tips auto pop
然后当#test 输入大于 3 有一个提示自动弹出
$('#test').on('input', function(e) {
this.setCustomValidity('')
if ($(this).val() > 3) {
this.setCustomValidity('wooo~~~~')
}
// e.target.checkValidity()
this.reportValidity();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input autofocus id='test' type="text" min="1" pattern="[0-9]+" required>
<!-- <button type="submit">submit</button> -->
</form>
回答by Alex
<input type="text" name="country" pattern="[A-z]{3}" oninput="this.reportValidity()" />
Check the oninput
bit.
检查oninput
位。
You might want to check older browsers though, something like:
不过,您可能想检查较旧的浏览器,例如:
<input type="text" name="country" pattern="[A-z]{3}"
oninput="if (typeof this.reportValidity === 'function') {this.reportValidity();}"/>
回答by Honza Zidek
The following jQuery code will force the validation every time the input is changed.
以下 jQuery 代码将在每次更改输入时强制进行验证。
It intercepts the oninput
eventon the <input...>
elements. If the value is invalid after the event, the change is undone and the original value is restored. It handles also situations where the invalid value has been pasted into the field.
它拦截元素上的oninput
事件<input...>
。如果事件发生后该值无效,则撤消更改并恢复原始值。它还处理无效值已粘贴到字段中的情况。
The data()
functionstores and retrieve any data to the element using the HTML5 data-attribute. The function stores the original value into the element data-last-valid
.
该data()
函数使用 HTML5 data-attribute存储和检索元素的任何数据。该函数将原始值存储到 element 中data-last-valid
。
<script lang="text/javascript">
// First "input" means event type `oninput`, second "input" is the CSS selector.
// So read as "for all <input ...> elements set the event handler
// for the "oninput" event to the function...
$(document).on("input", "input", function (event) {
if (this.checkValidity()) {
// Store the current valid value for future use
$(this).data('last-valid', this.value);
}
else {
// Undo the change using the stored last valid value
this.value = $(this).data('last-valid') || "";
}
});
</script>
回答by Loren
If you would like to use jQuery to backport the pattern functionality to older browsers like IE8, you could do something like:
如果您想使用 jQuery 将模式功能向后移植到 IE8 等较旧的浏览器,您可以执行以下操作:
// Jquery Function to Validate Patterns on Input Objects
(function( $ ){
$.fn.validatePattern = function(search) {
// Get the current element's siblings
var pattern = this.attr('pattern');
var value = this.val();
return !(pattern&&(value.length>0)&&!value.match( new RegExp('^'+pattern+'$') ));
};
})( jQuery );
$(document).ready(function() {
// Bind pattern checking (invalid) to on change
$(':input').change(function() {
if (!$(this).validatePattern()) {
$(this).addClass('invalidPattern');
}
});
// Bind pattern valid to keyUp
$(':input').keyUp(function() {
if ($(this).validatePattern()) {
$(this).removeClass('invalidPattern');
}
});
});
This will add the class invalidPattern to input objects which have a pattern and do not match it. You might also want to add checks for required, etc and on submit checks for the form to prevent submission if patterns don't validate. What I put above is a quick, light script to validate only the pattern.
这会将类 invalidPattern 添加到具有模式但不匹配的输入对象。您可能还想添加对必需等的检查,并在提交表单检查以防止在模式未验证时提交。我上面放的是一个快速、轻量级的脚本,用于仅验证模式。
For a more fully functional shim, look at http://adodson.com/jquery.form.js/
如需功能更齐全的垫片,请查看http://adodson.com/jquery.form.js/
The pattern validation code is from that project.
模式验证代码来自该项目。
回答by Hardik Sondagar
You should use keyup, focus and blur function to implement your need. For example:
您应该使用 keyup、focus 和 blur 功能来实现您的需求。例如:
you have input field for password:
您有密码输入字段:
<input id="pswd" type="password" required name="pswd" />
<input id="pswd" type="password" required name="pswd" />
In JavaScript Code :
在 JavaScript 代码中:
$('input[type=password]').keyup(function() {
// keyup event code here with validation rules });
$('input[type=password]').focus(function() {
// focus code here to show message which contains rules for input field });
$('input[type=password]').blur(function() {
// blur code here });
回答by kylex
Have you taken a a look at javascript's 'onkey' functions?
你看过javascript的'onkey'函数吗?
onkeyup
may be the one you are looking for if you want something as the user types.
onkeyup
如果您想要用户键入的内容,可能就是您正在寻找的那个。
In addtion, onchange
occurs when the field loses focus, while onkeyup
is fired as the user types. Depends on which you need.
此外,onchange
当字段失去焦点时发生,而onkeyup
在用户键入时触发。取决于你需要哪个。
You many wanna try something like this:
你们很多人都想尝试这样的事情:
onchange = variable.validate(this.value)
onchange = variable.validate(this.value)
回答by tfmontague
My suggestion is to prevent the user from entering invalid characters into an input in the first place, so they don't have to go back and correct the form.
我的建议是首先防止用户在输入中输入无效字符,这样他们就不必返回并更正表单。
<label for="test">Only accepts 'a' characters</label>
<input id="test" type="text"
placeholder="aa" pattern="[a]{1,2}" maxlength="2"
oninput="if (!this.checkValidity()) this.value = this.value.slice(0, -1)" />