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