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

JavascriptJqueryFormsHtml

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

I think its simpler:

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

this will stop the submit until form is valid.

Solution 10 - Javascript

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

Solution 11 - Javascript

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>

Solution 12 - Javascript

Try HTMLFormElement.reportValidity() where this function will invoke the input validations.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattias WolffView Question on Stackoverflow
Solution 1 - JavascriptDraughtGlobeView Answer on Stackoverflow
Solution 2 - JavascriptmhmView Answer on Stackoverflow
Solution 3 - JavascriptRick LiddleView Answer on Stackoverflow
Solution 4 - Javascriptjohn.dou.2011View Answer on Stackoverflow
Solution 5 - JavascriptDayron GallardoView Answer on Stackoverflow
Solution 6 - JavascriptShannon HochkinsView Answer on Stackoverflow
Solution 7 - Javascriptp5yk0View Answer on Stackoverflow
Solution 8 - JavascriptKarl AdlerView Answer on Stackoverflow
Solution 9 - JavascriptaleXelaView Answer on Stackoverflow
Solution 10 - Javascriptsms247View Answer on Stackoverflow
Solution 11 - JavascriptNadi hView Answer on Stackoverflow
Solution 12 - JavascriptLex FeriaView Answer on Stackoverflow