I am using ajax to invoke insert and update, so there are insert/update buttons instead of submit buttons (input type="submit"). Actually, I am using AngularJS, but the problem would be the same even if I was just using javaScript/ajax. The problem is that when I execute this javaScript code to programmatically submit the form (see below), HTML5 validation errors are not being shown to the user. HTML5 validation errors seem only to be shown when a submit button is actually clicked (as I saw in may posts and also verified for myself).
document.myform.submit();
After much effort, I finally found a simple/direct solution that worked for me, so I wanted to share it. What I did was have the insert and the update javaScript functions check the form's validity: if the form is valid, proceed with the ajax call to insert or update; otherwise, trigger the click event on a hidden submit button (input type="submit").
Here is my solution code. If anyone has any suggestions or comments, please let me know.
<!DOCTYPE html>
<html>
<body>
<form id="personForm" name="personForm">
Name:
<input type="text" name="Name" id="Name"
placeholder="Name" required />
Age:
<input type="number" name="Age" id="Age"
placeholder="Age" required />
<input type="button" value="update" onclick="doUpdate();"/>
<input type="button" value="insert" onclick="doInsert();"/>
<!-- hidden submit button -->
<div style="display:none;">
<input type="submit" id="submitButton"/>
</div>
<script>
function $(element) {
return document.getElementById(element);
}
function doUpdate() {
// if form is invalid...
if (!$("personForm").checkValidity()) {
// auto click the submit button which is the only
// way to get html5 show validation errors to user.
// Due to errors, it will not actually submit.
$("submitButton").click();
} else {
alert("make ajax call for update");
}
}
function doInsert() {
// if form is invalid...
if (!$("personForm").checkValidity()) {
// auto click the submit button which is the only
// way to get html5 show validation errors to user.
// Due to errors, it will not actually submit.
$("submitButton").click();
} else {
alert("make ajax call for insert");
}
}
</script>
</form>
</body>
</html>