Javascript 触发 HTML5 表单验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7548612/
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
Triggering HTML5 Form Validation
提问by Drew
I have a form with several different fieldsets. I have some Javascript that displays the field sets to the users one at a time. For browsers that support HTML5 validation, I'd love to make use of it. However, I need to do it on my terms. I'm using JQuery.
我有一个包含几个不同字段集的表单。我有一些 Javascript 一次向用户显示字段集。对于支持 HTML5 验证的浏览器,我很乐意使用它。但是,我需要按照我的条件去做。我正在使用 JQuery。
When a user clicks a JS Link to move to the next fieldset, I need the validation to happen on the current fieldset and block the user from moving forward if there is issues.
当用户单击 JS 链接移动到下一个字段集时,我需要在当前字段集上进行验证,并在出现问题时阻止用户继续前进。
Ideally, as the user loses focus on an element, validation will occur.
理想情况下,当用户失去对元素的关注时,就会发生验证。
Currently have novalidate going and using Javascript. Would prefer to use the native method. :)
目前有 novalidate 去和使用 Javascript。更愿意使用本机方法。:)
采纳答案by robertc
You can't trigger the native validation UI, but you can easily take advantage of the validation API on arbitrary input elements:
您无法触发本机验证 UI,但您可以轻松利用任意输入元素上的验证 API:
$('input').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The first event fires checkValidity
on every input element as soon as it loses focus, if the element is invalid
then the corresponding event will be fired and trapped by the second event handler. This one sets the focus back to the element, but that could be quite annoying, I assume you have a better solution for notifying about the errors. Here's a working example of my code above.
checkValidity
一旦失去焦点,第一个事件就会在每个输入元素上触发,如果元素是,invalid
则相应的事件将被第二个事件处理程序触发并捕获。这将焦点放回到元素上,但这可能很烦人,我假设您有更好的解决方案来通知错误。 这是我上面代码的一个工作示例。
回答by Loilo
TL;DR:Not caring about old browsers? Use form.reportValidity()
.
TL;DR:不关心旧浏览器?使用form.reportValidity()
.
Need legacy browser support? Read on.
需要旧版浏览器支持?继续阅读。
It actually ispossible to trigger validation manually.
它实际上是可能触发验证手动。
I'll use plain JavaScript in my answer to improve reusability, no jQuery is needed.
我将在答案中使用纯 JavaScript 来提高可重用性,不需要 jQuery。
Assume the following HTML form:
假设以下 HTML 表单:
<form>
<input required>
<button type="button">Trigger validation</button>
</form>
And let's grab our UI elements in JavaScript:
让我们在 JavaScript 中获取我们的 UI 元素:
var form = document.querySelector('form')
var triggerButton = document.querySelector('button')
Don't need support for legacy browsers like Internet Explorer? This is for you.
不需要对 Internet Explorer 等旧浏览器的支持?这个给你。
All modern browsers supportthe reportValidity()
method on form
elements.
所有现代浏览器都支持元素reportValidity()
上的方法form
。
triggerButton.onclick = function () {
form.reportValidity()
}
That's it, we're done. Also, here's a simple CodePenusing this approach.
就是这样,我们完成了。此外,这是一个使用这种方法的简单 CodePen。
Approach for older browsers
旧浏览器的方法
Below is a detailed explanation how
reportValidity()
can be emulated in older browsers.However, you don't need to copy&paste those code blocks into your project yourself — there is a ponyfill/polyfillreadily available for you.
下面是如何
reportValidity()
在旧浏览器中模拟的详细说明。
Where reportValidity()
is not supported, we need to trick the browser a little bit. So, what will we do?
哪里reportValidity()
不支持,我们需要稍微欺骗浏览器。那么,我们会怎么做?
- Check validity of the form by calling
form.checkValidity()
. This will tell us if the form is valid, but not show the validation UI. - If the form is invalid, we create a temporary submit button and trigger a click on it. Since the form is not valid, we knowit won't actuallysubmit, however, it will show validation hints to the user. We'll remove the temporary submit button immedtiately, so it will never be visible to the user.
- If the form is valid, we don't need to interfere at all and let the user proceed.
- 通过调用检查表单的有效性
form.checkValidity()
。这将告诉我们表单是否有效,但不会显示验证 UI。 - 如果表单无效,我们会创建一个临时提交按钮并触发对其的点击。由于表单无效,我们知道它实际上不会提交,但是,它会向用户显示验证提示。我们将立即删除临时提交按钮,因此它永远不会对用户可见。
- 如果表单有效,我们根本不需要干预,让用户继续。
In code:
在代码中:
triggerButton.onclick = function () {
// Form is invalid!
if (!form.checkValidity()) {
// Create the temporary button, click and remove it
var tmpSubmit = document.createElement('button')
form.appendChild(tmpSubmit)
tmpSubmit.click()
form.removeChild(tmpSubmit)
} else {
// Form is valid, let the user proceed or do whatever we need to
}
}
This code will work in pretty much any common browser (I've tested it successfully down to IE11).
这段代码几乎可以在任何常见的浏览器中工作(我已经成功测试到 IE11)。
回答by Xieranmaya
In some extent, You CAN trigger
HTML5 form validation and show hints to user without submitting the form!
在某种程度上,您可以在trigger
不提交表单的情况下进行 HTML5 表单验证并向用户显示提示!
Two button, one for validate, one for submit
两个按钮,一个用于验证,一个用于提交
Set a onclick
listener on the validate button to set a global flag(say justValidate
) to indicate this click is intended to check the validation of the form.
onclick
在验证按钮上设置一个侦听器以设置全局标志(例如justValidate
)以指示此单击旨在检查表单的验证。
And set a onclick
listener on the submit button to set the justValidate
flag to false.
并onclick
在提交按钮上设置一个侦听器以将justValidate
标志设置为 false。
Then in the onsubmit
handler of the form, you check the flag justValidate
to decide the returning value and invoke the preventDefault()
to stop the form to submit. As you know, the HTML5 form validation(and the GUI hint to user) is preformed before the onsubmit
event, and even if the form is VALID you can stop the form submit by returning false or invoke preventDefault()
.
然后在onsubmit
表单的处理程序中,您检查标志justValidate
以决定返回值并调用preventDefault()
以停止表单提交。如您所知,HTML5 表单验证(以及对用户的 GUI 提示)是在onsubmit
事件之前执行的,即使表单是 VALID,您也可以通过返回 false 或 invoke 来停止表单提交preventDefault()
。
And, in HTML5 you have a method to check the form's validation: the form.checkValidity()
, then in you can know if the form is validate or not in your code.
而且,在 HTML5 中,您有一种检查表单验证的方法:form.checkValidity()
,然后在您的代码中您可以知道表单是否已验证。
OK, here is the demo: http://jsbin.com/buvuku/2/edit
好的,这里是演示:http: //jsbin.com/buvuku/2/edit
回答by Anatoli Papirovski
I'm not sure it's worth it for me to type this all up from scratch since this article published in A List Apartdoes a pretty good job explaining it. MDN also has a handy guidefor HTML5 forms and validation (covering the API and also the related CSS).
我不确定是否值得我从头开始输入这些内容,因为A List Apart上发表的这篇文章很好地解释了它。MDN 还有一个方便的 HTML5 表单和验证指南(包括 API 和相关的 CSS)。
回答by wreleven
Somewhat easy to make add or remove HTML5 validation to fieldsets.
对字段集添加或删除 HTML5 验证有点容易。
$('form').each(function(){
// CLEAR OUT ALL THE HTML5 REQUIRED ATTRS
$(this).find('.required').attr('required', false);
// ADD THEM BACK TO THE CURRENT FIELDSET
// I'M JUST USING A CLASS TO IDENTIFY REQUIRED FIELDS
$(this).find('fieldset.current .required').attr('required', true);
$(this).submit(function(){
var current = $(this).find('fieldset.current')
var next = $(current).next()
// MOVE THE CURRENT MARKER
$(current).removeClass('current');
$(next).addClass('current');
// ADD THE REQUIRED TAGS TO THE NEXT PART
// NO NEED TO REMOVE THE OLD ONES
// SINCE THEY SHOULD BE FILLED OUT CORRECTLY
$(next).find('.required').attr('required', true);
});
});
回答by chenxin
I seem to find the trick:
Just remove the form target
attribute, then use a submit button to validate the form and show hints, check if form valid via JavaScript, and then post whatever. The following code works for me:
我似乎找到了诀窍:只需删除表单target
属性,然后使用提交按钮验证表单并显示提示,通过 JavaScript 检查表单是否有效,然后发布任何内容。以下代码对我有用:
<form>
<input name="foo" required>
<button id="submit">Submit</button>
</form>
<script>
$('#submit').click( function(e){
var isValid = true;
$('form input').map(function() {
isValid &= this.validity['valid'] ;
}) ;
if (isValid) {
console.log('valid!');
// post something..
} else
console.log('not valid!');
});
</script>
回答by H?ng Tr?nh
Html Code:
html代码:
<form class="validateDontSubmit">
....
<button style="dislay:none">submit</button>
</form>
<button class="outside"></button>
javascript( using Jquery):
javascript(使用Jquery):
<script type="text/javascript">
$(document).on('submit','.validateDontSubmit',function (e) {
//prevent the form from doing a submit
e.preventDefault();
return false;
})
$(document).ready(function(){
// using button outside trigger click
$('.outside').click(function() {
$('.validateDontSubmit button').trigger('click');
});
});
</script>
Hope this will help you
希望能帮到你
回答by Ilya webdev
var field = $("#field")
field.keyup(function(ev){
if(field[0].value.length < 10) {
field[0].setCustomValidity("characters less than 10")
}else if (field[0].value.length === 10) {
field[0].setCustomValidity("characters equal to 10")
}else if (field[0].value.length > 10 && field[0].value.length < 20) {
field[0].setCustomValidity("characters greater than 10 and less than 20")
}else if(field[0].validity.typeMismatch) {
field[0].setCustomValidity("wrong email message")
}else {
field[0].setCustomValidity("") // no more errors
}
field[0].reportValidity()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="email" id="field">
回答by Nadi h
When there is a very complex (especially asynchronous) validation process, there is a simple workaround:
当有一个非常复杂(尤其是异步)的验证过程时,有一个简单的解决方法:
<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
var form1 = document.forms['form1']
if (!form1.checkValidity()) {
$("#form1_submit_hidden").click()
return
}
if (checkForVeryComplexValidation() === 'Ok') {
form1.submit()
} else {
alert('form is invalid')
}
}
</script>
回答by Vasyl Boiko
Another way to resolve this problem:
解决此问题的另一种方法:
$('input').oninvalid(function (event, errorMessage) {
event.target.focus();
});