[javascript] 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.

This question is related to javascript jquery forms html

The answer is


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.


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

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

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


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.


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>

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


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


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment