最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validate Html 5 input without form tag? - Stack Overflow

programmeradmin5浏览0评论

Is it possible to trigger browser built-in html 5 validation process without form tag? I want to show the browser error messages if my input control is invalid without using form tag. I know I can check validation using checkValidity function but how to tell browser to trigger validation process?

Is it possible to trigger browser built-in html 5 validation process without form tag? I want to show the browser error messages if my input control is invalid without using form tag. I know I can check validation using checkValidity function but how to tell browser to trigger validation process?

Share Improve this question asked Feb 10, 2015 at 7:41 Imran Qadir Baksh - BalochImran Qadir Baksh - Baloch 34k69 gold badges194 silver badges347 bronze badges 1
  • 1 I doubt that this is possible. For one, it is specifically defined as form validation in the HTML5 spec. And secondly, since validation is triggered when the form is submitted, I don’t see how it should be triggered in your case. – C3roe Commented Feb 10, 2015 at 7:50
Add a ment  | 

3 Answers 3

Reset to default 7

I agree with CBroe , I'm not sure you can use HTML5 form validation without a actual form.. I've found this link and it should be of some use to you:

https://stackoverflow./a/7562439/4092442

You can't trigger the native validation UI, but you can easily take advantage of the validation API on arbitrary input elements:

$('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. If that does not help, perhaps you can get creative and create a form, that doesn't look like a form. Hide the submit button etc. That way you can take advantage of the functionality.

Also, maybe provide a little more explanation as to what it is you're trying to acplish. I have personally found that helps people offer detailed solutions. Solutions I often never even considered. :) Hope this helps!

This is absolutely possible using .reportValidity(), not sure why the other answers said it isn't. An example to check all inputs for validity:

document.querySelectorAll('input').forEach(e => e.reportValidity())

Later, but it can be help to news search.

You can use

$(elem)[0].reportValidity()

发布评论

评论列表(0)

  1. 暂无评论