Validate html form with javascript after html automatic validation - javascript

I have to make a little form with some fields like name, age or email. For example:
<input id="name" type="text" required/>
I have a problem with the validation because i want to use the automatic validation of html to check that all fields with the required tag aren't empty and, after that, validate some fields (like the email) with javascript. I have a submit input element like this:
<input type="submit" value="Submit" onclick="form.validate()" />
The problem is that the onclick method (validate()) is always called before the auto validation, and what i want to do is call that method afther the auto validation ends (and it's everything right). The javascript i'm using to test looks like this:
"use strict";
class Form {
constructor(){}
validate(){
alert("validate");
}
}
var form = new Form();
The alert is always shown, but the auto validation it's not. If i don't put the onclick tag with its method on the submit button, the auto validation works. Any idea about my problem?

You need to use the directive ng-submit in your form:
<form ng-submit="form.validate()" ng-controller="YourController">
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>
https://docs.angularjs.org/api/ng/directive/ngSubmit
https://docs.angularjs.org/api/ng/directive/form#submitting-a-form-and-preventing-the-default-action
Keep Rocking!

This method uses jQuery. First you need to prevent the default action on form submit, then you can do your validation, then finally submit the form. Example below.
Your form:
<form id="form">
<input type="text" required>
<input type="submit" value="Submit!">
</form>
Javascript(with jQuery):
$('#form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
form.validate();
alert('here');
this.submit(); // If all the validations succeeded
});
JavaScript(vanilla):
document.getElementById('form').addEventListener('submit', function(ev) {
ev.preventDefault(); // to stop the form from submitting
/* Validations go here */
alert('here');
this.submit(); // If all the validations succeeded
});

Related

i am using required html tag for input fields but its not working [duplicate]

I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

How to execute a set of JavaScript code only if HTML form validation is succesfull

I have a HTML form with some fields and a submit button. couple of fields are mandatory. I have a set of JavaScript code which i need to execute only if the form validation is successful. If there is some validation error on the form, the JavaScript code shall not execute. Below is the sample code:
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
/*JavaScript*/
$("#sampleForm").submit(function(){
//Set of JavaScript code to execute if validation is success.
});
For me above JavaScript code does not work.
Please help!
In a comment you've said:
But if i use $("#sampleForm").submit() to submit the form, the form gets submitted but if i write function inside submit() ($("#sampleForm").submit(function(){ //Set of JavaScript code to execute if validation is success. });) then nothing happens !
That function is called when the submit event is fired, but the event isn't fire when the controls are invalid because the form won't be submitted.
The individual form controls get an invalid event when the user tries to submit the form when they're invalid. You can use that to provide feedback beyond what the browser supplies if you like:
$("#sampleform")
.on("submit", function() {
alert("Got the 'submit' event; form is being submitted");
})
.find("input, select")
.on("invalid", function() {
// Will fire for *EACH* invalid control
alert("Validation failed");;
});
Fiddle (Stack Snippets don't allow form submission even when it's cancelled.)
In case you need to submit the form programmatically (by calling submit), you can use checkValidity first to see if the form is valid:
// When submitting programmatically
var form = $("#sampleForm");
if (form[0].checkValidity()) {
form.submit();
}
Side note: When you use jQuery to submit the form (above), submit event handlers will be called. But if you use the DOM to submit the form ($("#sampleForm)[0].submit()), they won't be.
Just write a submit handler and execute your codes.
$("#sampleForm").submit(function(){
// Your code.
})
Submit handler triggers only when you complete the validation by HTML5 custom validator.
Here is a demo : http://jsfiddle.net/sureshatta/9ky8Z/118/
Html5 form have checkValidity method.Also since it is a form and button type is submit it will default throw an error pop up if it is not valid. checkValidity method return a boolean value true if it is valid. You can take a look in this method for further your job
$("#sampleForm").submit(function(e) {
var result = document.getElementById('firstname').checkValidity()
console.log(result) // will log true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
Thanks everyone for the answers!
I tried each one of your's solution which helped me to reach to my solution. Below worked for me:
if($("#sampleForm").valid()){
$("#sampleForm").submit();
//Set of JavaScript code to execute.
}

Validate input type=number min=... single field, no form [duplicate]

I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?
This is the HTML code:
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
I'm submitting the form in the function submitform().
The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()) {
f.submit();
} else {
alert(document.getElementById('example').validationMessage);
}
}
You should use form tag enclosing your inputs. And input type submit.
This works.
<form id="testform">
<input type="text" id="example" name="example" required>
<button type="submit" onclick="submitform()" id="save">Save</button>
</form>
Since HTML5 Validation works only with submit button you have to keep it there.
You can avoid the form submission though when valid by preventing the default action by writing event handler for form.
document.getElementById('testform').onsubmit= function(e){
e.preventDefault();
}
This will give your validation when invalid and will not submit form when valid.
I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):
<input type="text" id="example" name="example" value="" required>
<button type="button" onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">
<script>
function submitform() {
$('#submit_handle').click();
}
</script>
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
https://jsfiddle.net/45vxjz87/1/
Either you can change the button type to submit
<button type="submit" onclick="submitform()" id="save">Save</button>
Or you can hide the submit button, keep another button with type="button" and have click event for that button
<form>
<button style="display: none;" type="submit" >Hidden button</button>
<button type="button" onclick="submitForm()">Submit</button>
</form>
Try with <button type="submit"> you can perform the functionality of submitform() by doing <form ....... onsubmit="submitform()">
2019 update: Reporting validation errors is now made easier than a the time of the accepted answer by the use of HTMLFormElement.reportValidity() which not only checks validity like checkValidity() but also reports validation errors to the user.
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
Updated solution snippet:
function submitform() {
var f = document.getElementsByTagName('form')[0];
if(f.reportValidity()) {
f.submit();
}
}
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try this out:
<script type="text/javascript">
function test
{
alert("hello world"); //write your logic here like ajax
}
</script>
<form action="javascript:test();" >
firstName : <input type="text" name="firstName" id="firstName" required/><br/>
lastName : <input type="text" name="lastName" id="lastName" required/><br/>
email : <input type="email" name="email" id="email"/><br/>
<input type="submit" value="Get It!" name="submit" id="submit"/>
</form>

Replace/Hide Input Button If Form Is Validated (Using jquery.validate.js)

I have this normal form:
<form class="vform" action='http://example.com/someaction.php' method='post' id='myid' >
<input type="email" name="email" id="email" class="required email " placeholder="Enter Your Email" >
<input id="#before" type='submit' value="Submit">
</form>
I am using the jquery.validate.js plugin to validate the form, which is working fine. (Link)
WHAT IS REQUIRED:
Before the user is redirected upon successful validation of the form, there is this 'pause' (while its redirecting)... during this time, users are repeatedly hitting the submit button.
How can I hide/replace (maybe with a loading gif or something) the submit button IF the form is validated.
Meaning, disable or replace the input button with something else IF the form is validated.
THE VALIDATION CODE:
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$(".vform").validate();
});
</script>
I tried adding some replacement/disable code after the validate function like this:
$(this).children('input[type=submit]').attr('disabled', 'disabled');
or
$('#before').replaceWith($('#after'));
But confused as to how to actually go about it.
Can anyone offer some insight?
EDIT: The input button shouldn't be replaced/disabled if the form validation is false
You can submitHandler of jQuery validate.
<script>
$(document).ready(function() {
$(".vform").validate({
submitHandler: function(form) { // <- pass 'form' argument in
$("#before").attr("disabled", true);
form.submit(); // <- use 'form' argument here.
}
});
});
</script>

Difference between form.submit() and having an input with type of "submit"

I have a HTML page containing a form. I want to make some fields "required". The problem is that I'm not using a <input type="submit"> in my form, instead, I use a Javascript function to submit the form because I need to send a Javascript variable to my server. Here is my code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="button" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
So, Even is I have the required attribute in my input but the form is still being submitted even if I don't enter anything in the input.
Here is a JSFiddle of how I want my form to behave when clicking on the button without entering anything.
Anyone knows how form.submit() is different from having an <input> of type="submit" ?
EDIT: After following user2696779's answer and doing a little modification, here's the final working code:
<form action="/toServer">
Username: <input type="text" name="usrname" required>
<input type="submit" onclick="submitForm(this.form)" value="Submit">
</form>
var submitForm = function(frm){
if (frm.checkValidity()) {
var qstNbr = document.getElementById('hiddenField');
qstNbr.value = someJsVariable;
frm.submit();
}
}
Your current HTML input button isn't a submit type, it's a button type. The requred attribute on your input element is therefore ignored. To change this, change your button's type to submit:
<input type="submit" value="Submit">
Browsers which support the required attribute will now display a warning when the button is clicked:
JSFiddle demo.
Submitting using javascript will not trigger any validation. If you want to submit using a regular button + javascript and still have validation, you may use HTML5's checkValidity function to verify form fields, or the entire form.
For example, using JQuery:
if(!$('form')[0].checkValidity()) {
alert('not valid');
}
else {
$('form').submit();
}
See fiddle for working example: http://jsfiddle.net/8Kmck/2/

Categories