Javascript 在不使用提交按钮的情况下触发标准的 HTML5 验证(表单)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7002230/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:13:48  来源:igfitidea点击:

Trigger standard HTML5 validation (form) without using submit button?

javascriptjqueryformshtml

提问by Mattias Wolff

Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button? (JavaScript or jQuery).

任何知道如何在不使用提交按钮的情况下在表单中触发标准 HTML5 验证的人?(JavaScript 或 jQuery)。

I do notwant to send POST/GETrequest, only do the validation.

希望发送POST/GET的请求,只能做验证。

采纳答案by Rick Liddle

The accepted answer to this questionappears to be what you're looking for.

这个问题的公认答案似乎是您正在寻找的。

Short summary: in the event handler for the submit, call event.preventDefault().

简短摘要:在提交的事件处理程序中,调用event.preventDefault().

回答by DraughtGlobe

After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

经过一番研究,我想出了以下代码,应该可以回答您的问题。(至少它对我有用)

Use this piece of code first. The $(document).readymakes sure the code is executed when the form is loaded into the DOM:

首先使用这段代码。在$(document).ready确保当表单加载到DOM中被执行的代码:

$(document).ready(function()
{
    $('#theIdOfMyForm').submit(function(event){
        if(!this.checkValidity())
        {
            event.preventDefault();
        }
    });
});

Then just call $('#theIdOfMyForm').submit();in your code.

然后只需调用$('#theIdOfMyForm').submit();您的代码。

UPDATE

更新

If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

如果您确实想显示用户在表单中的哪个字段出错,请在后面添加以下代码 event.preventDefault();

$('#theIdOfMyForm :input:visible[required="required"]').each(function()
{
    if(!this.validity.valid)
    {
        $(this).focus();
        // break
        return false;
    }
});

It will give focus on the first invalid input.

它将关注第一个无效输入。

回答by mhm

You can use reportValidity, however it has poor browser support yet. It works on Chrome, Opera and Firefox but not on IE nor Edge or Safari:

您可以使用reportValidity,但是它的浏览器支持还很差。它适用于 Chrome、Opera 和 Firefox,但不适用于 IE、Edge 或 Safari:

var myform = $("#my-form")[0];
if (!myform.checkValidity()) {
    if (myform.reportValidity) {
        myform.reportValidity();
    } else {
        //warn IE users somehow
    }
}

(checkValidityhas better support, but does not work on IE<10 neither.)

checkValidity有更好的支持,但不适用于 IE<10。)

回答by john.dou.2011

You have to submit the form to get the html5 validation to work. There's a way around it to get what you want. Se the code:

您必须提交表单才能使 html5 验证工作。有一种方法可以解决它来获得您想要的东西。看代码:

<body>
    <h1>Validation Example</h1><br />
    <h2>Insert just 1 digit<h2>
    <form id="form" onsubmit="return false">
        <label>Input<input type="text" pattern="[0-9]" id="input" /></label> 
        <input type="submit" class="hide" id="inputButton">         
    </form>
</body>

See an example here

在此处查看示例

Note: using form.submit() didn't work for me. So i created a hidden submit button, that triggers on keyup. Don't ask me why. Maybe someone could clarify it.

注意:使用 form.submit() 对我不起作用。所以我创建了一个隐藏的提交按钮,它在 keyup 上触发。不要问我为什么。也许有人可以澄清它。

回答by Dayron Gallardo

This is my implementation of the solution suggested by @mhm, where I discarded the use of jQuery.

这是我对@mhm 建议的解决方案的实现,在那里我放弃了 jQuery 的使用。

The variable formId contains the id of the form and msg is an object with messages of my application.

变量 formId 包含表单的 id,而 msg 是一个包含我的应用程序消息的对象。

This implementation tries to notify the user with the native HTML 5 error messages, if not possible then alert a generic form error message.

此实现尝试使用本机 HTML 5 错误消息通知用户,如果不可能,则警告通用表单错误消息。

If there are no errors I submit the form.

如果没有错误,我提交表单。

let applyForm = document.getElementById(formId);

if (!applyForm.checkValidity()) {
  if (applyForm.reportValidity) {
    applyForm.reportValidity();
  } else {
    alert(msg.ieErrorForm);
  }
} else {
  applyForm.submit();
}

回答by Shannon Hochkins

Short answer, no, there's no way to 'trigger' the default functionality of the html5 bubble inline before submission of the form, you can checkValidity()on certain inputs, but again doesn't work as you would want. Short of preventing the default if you still want to submit the form once validation is complete, you can still process this style by doing the following:

简短的回答,不,在提交表单之前,无法“触发”内联 html5 气泡的默认功能,您可以checkValidity()对某些输入进行操作,但同样无法按您的意愿工作。如果您在验证完成后仍想提交表单,则无需阻止默认设置,您仍然可以通过执行以下操作来处理此样式:

Note, on forms you don't want the validation css styles to be applied, you can simply add the novalidateattribute to the form.

请注意,在您不希望应用验证 css 样式novalidate的表单上,您可以简单地将属性添加到表单中。

HTML:

HTML:

<form name="login" id="loginForm" method="POST">
    <input type="email" name="username" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <input type="submit" value="LOG IN" class="hero left clearBoth">
</form>

If you're not using SCSS, I would highly recommend looking into it, it's much more manageable, easy to write and less convoluted. Note: In the fiddle example, i do have the exact css that this will compile. I've also included a bubble style example.

如果您不使用 SCSS,我强烈建议您研究它,它更易于管理、易于编写且不那么复杂。注意:在小提琴示例中,我确实有将编译的确切 css。我还包含了一个气泡样式示例。

SCSS:

社会保障:

form:not([novalidate])            {
  input, textarea                 {
    &:required                    {background: transparent url('/../../images/icons/red_asterisk.png') no-repeat 98% center;}
    &:required:valid              {background: transparent url('/../../images/icons/valid.png') no-repeat 98% center; @include box-shadow(0 0 5px #5cd053);border-color: #28921f;}
    &:not(:focus):valid           {box-shadow: none;border: 1px solid $g4;}
    &:focus:invalid               {background: transparent url('/../../images/icons/invalid.png') no-repeat 98% center;  @include box-shadow(0 0 5px #d45252); border-color: #b03535}  
  }
}
span.formHintBubble {position:absolute; background:$g7; margin-top:50px;@include borderRadius(10px); padding:5px 40px 5px 10px; color:white; @include opacity(0.9); @include box-shadow(1px 1px 6px 1px rgba(0,0,0,0.2));
  &:after {
     @include triangle(30px, $g7, up); content: " "; margin-bottom:27px; left:25px;
  }
  .cross {background:black; border:1px solid $g3; @include borderRadius(10px); width:15px; height:15px; color:#fff; display:block; line-height:15px; position:absolute; right:5px; top:50%; margin-top:-7.5px; padding:0; text-align:center; font-size:10px; cursor:pointer;}
}

JAVASCRIPT:

爪哇脚本:

Here, we can do some funky stuff to use the default messages and inherit them inside your own 'bubble' or error message box.

在这里,我们可以做一些时髦的事情来使用默认消息并在您自己的“气泡”或错误消息框中继承它们。

var form    = $('form');
var item    = form.find(':invalid').first();
var node    = item.get(0);                       
var pos     = item.position();                
var message = node.validationMessage || 'Invalid value.'; 
var bubble  = $('<span/>').html('<span class="formHintBubble" style="left: ' + pos.left  + 'px; top:' + pos.top + 'px;">' + message + '<div class="cross">X</div></span>').contents();        
bubble.insertAfter(item); 

DEMO:

演示:

http://jsfiddle.net/shannonhochkins/wJkVS/

http://jsfiddle.net/shannonhochkins/wJkVS/

Enjoy and I hope I help others with HTML5 form validation as it's awesome, and it needs to get out there!

享受吧,我希望我能帮助其他人进行 HTML5 表单验证,因为它很棒,它需要走出去!

Shannon

香农

回答by aleXela

I think its simpler:

我认为它更简单:

$('submit').click(function(e){
if (e.isValid())
   e.preventDefault();
//your code.
}

this will stop the submit until form is valid.

这将停止提交,直到表单有效。

回答by p5yk0

form.submit() doesn't work cause the HTML5 validation is performed before the form submition. When you click on a submit button, the HTML5 validation is trigerred and then the form is submited if validation was successfull.

form.submit() 不起作用,因为在提交表单之前执行 HTML5 验证。当您单击提交按钮时,会触发 HTML5 验证,然后如果验证成功则提交表单。

回答by Karl Adler

As stated in the other answers use event.preventDefault() to prevent form submitting.

如其他答案中所述,使用 event.preventDefault() 来防止表单提交。

To check the form before I wrote a little jQuery function you may use (note that the element needs an ID!)

在我编写一个你可以使用的小 jQuery 函数之前检查表单(注意元素需要一个 ID!)

(function( $ ){
    $.fn.isValid = function() {
        return document.getElementById(this[0].id).checkValidity();
    };
})( jQuery );

example usage

示例用法

 $('#submitBtn').click( function(e){

        if ($('#registerForm').isValid()){
            // do the request
        } else {
            e.preventDefault();
        }
    });

回答by sms247

i was using

我正在使用

objectName.addEventListener('click', function() {
event.preventDefault();
}

but its show error "event is undefined" so in this case use event parameter like

但它的显示错误“事件未定义”所以在这种情况下使用事件参数,如

objectName.addEventListener('click', function(event) {
event.preventDefault();
}

now its works fine

现在它工作正常