简体   繁体   English

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

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

Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button?谁知道我如何在不使用提交按钮的情况下在表单中触发标准 HTML5 验证? (JavaScript or jQuery). (JavaScript 或 jQuery)。

I do not want to send POST/GET request, only do the validation.不想发送POST/GET请求,只做验证。

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).ready makes 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();然后只需调用$('#theIdOfMyForm').submit(); in your code.在你的代码中。

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.它将重点放在第一个无效输入上。

You can use reportValidity , however it has poor browser support yet.您可以使用reportValidity ,但是它的浏览器支持还很差。 It works on Chrome, Opera and Firefox but not on IE nor Edge or Safari:它适用于 Chrome、Opera 和 Firefox,但不适用于 IE、Edge 或 Safari:

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

( checkValidity has better support, but does not work on IE<10 neither.) checkValidity有更好的支持,但也不适用于 IE<10。)

The accepted answer to this question appears to be what you're looking for. 这个问题的公认答案似乎是您正在寻找的。

Short summary: in the event handler for the submit, call event.preventDefault() .简短摘要:在提交的事件处理程序中,调用event.preventDefault()

You have to submit the form to get the html5 validation to work.您必须提交表单才能使 html5 验证生效。 There's a way around it to get what you want.有一种方法可以得到你想要的。 Se the code:查看代码:

<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.注意:使用 form.submit() 对我不起作用。 So i created a hidden submit button, that triggers on keyup.所以我创建了一个隐藏的提交按钮,它在 keyup 上触发。 Don't ask me why.不要问我为什么。 Maybe someone could clarify it.也许有人可以澄清一下。

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 是一个 object,其中包含我的应用程序的消息。

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();
}

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

Note, on forms you don't want the validation css styles to be applied, you can simply add the novalidate attribute to the form.注意,在 forms 上,您不希望应用验证 css styles,您可以简单地将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.如果您不使用 SCSS,我强烈建议您研究一下,它更易于管理、易于编写且不那么复杂。 Note: In the fiddle example, i do have the exact css that this will compile.注意:在小提琴示例中,我确实有将编译的确切 css。 I've also included a bubble style example.我还包含了一个气泡样式示例。

SCSS: 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: 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香农

form.submit() doesn't work cause the HTML5 validation is performed before the form submition. form.submit() 不起作用,因为在提交表单之前执行了 HTML5 验证。 When you click on a submit button, the HTML5 validation is trigerred and then the form is submited if validation was successfull.当您单击提交按钮时,将触发 HTML5 验证,如果验证成功,则提交表单。

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 function 你可以使用(注意元素需要一个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();
        }
    });

I think its simpler:我认为它更简单:

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

this will stop the submit until form is valid.这将停止提交,直到表单有效。

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现在它工作正常

I know it is an old topic, but 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>

Try HTMLFormElement.reportValidity() where this function will invoke the input validations.试试 HTMLFormElement.reportValidity(),这个 function 将调用输入验证。

A fun way to validate the form, section-by-section, without using the submit button...sort of.一种有趣的方式来验证表单,逐个部分,而不使用提交按钮......排序。

Run checkValidity() on every input in the active section.对活动部分中的每个输入运行 checkValidity()。 If we find one that fails, we do submitbutton.click() to activate the browser's built-in notification.如果我们发现一个失败,我们执行 submitbutton.click() 来激活浏览器的内置通知。

Since we're only running submitbutton.click() if we detected a failure, we don't accidentally submit the form.由于我们仅在检测到失败时才运行 submitbutton.click(),因此我们不会意外提交表单。

In practice, the browser notifies the user before we can proceed to the next section.在实践中,浏览器会在我们继续下一节之前通知用户。

Html: Html:

<form id="myform">
    <div>
        <input type="text" name="blah1" required />
        <input type="text" name="blah2" required />
    </div>
    <div class="hidden">
        <input type="text" name="blah3" required />
        <input type="text" name="blah4" required />
    </div>
    <input type="button" id="nextbutton" name="nextbutton" value="Next" />
    <input type="submit" id="submitbutton" name="send" value="Submit" />
</form>

Javascript: Javascript:

var viewing = 0;
var formSection = document.getElementById("myform").getElementsByTagName("div");
var submitbutton = document.getElementById("submitbutton");
document.getElementById("nextbutton").onclick = function() {viewFormSection(viewing + 1);}

function sectionValid(section)
{
    var tempInputs = formSection[section].querySelectorAll("input, select, textarea");
    for(var i = 0; i < tempInputs.length; i++)
    {
        if(!tempInputs[i].checkValidity())
        {
            return false;
        }
    }
    return true;
}

function viewFormSection(section)
{
    //Validate the current section before proceeding.
    if(!sectionValid(viewing))
    {
        submitbutton.click();
        return false;
    }

    //Code that hides the current form section and shows the desired one.
    viewing == section;
}

HTML will generate errors on the hidden fields in sections that you haven't gotten to yet, because it doesn't like that they can't be focused. HTML 将在您尚未到达的部分中的隐藏字段上生成错误,因为它不喜欢它们无法集中。 But by the time you get to the last section, it won't be a problem anymore.但是当你到达最后一部分时,它就不再是问题了。

This works on Internet Explorer, whereas reportValidity() does not.这适用于 Internet Explorer,而 reportValidity() 不适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM