简体   繁体   中英

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? (JavaScript or jQuery).

I do not want to send POST/GET request, only do the validation.

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(function()
{
    $('#theIdOfMyForm').submit(function(event){
        if(!this.checkValidity())
        {
            event.preventDefault();
        }
    });
});

Then just call $('#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();

$('#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. It works on Chrome, Opera and Firefox but not on IE nor Edge or 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.)

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() .

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:

<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.

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

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

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

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. 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.

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:

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/

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

Shannon

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.

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

To check the form before I wrote a little jQuery function you may use (note that the element needs an 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.

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. If we find one that fails, we do submitbutton.click() to activate the browser's built-in notification.

Since we're only running submitbutton.click() if we detected a failure, we don't accidentally submit the form.

In practice, the browser notifies the user before we can proceed to the next section.

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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