Reputation: 2591
I do not want to perform a submit action when pressing the "submit" button on my form but rather perform some data manipulation and then submit the form using javascript form.submit
- as such I do not use the
element in my form:<input type="submit">
<form action="process.php" method="post" name="myForm">
<input type="text" name="entry" id="entry" required />
<input type="button" value="Submit" onclick="manipulate_and_submit(this.form, this.form.entry);" />
</form>
With the script being something like:
function manipulate_and_submit(form, entry) {
var val = entry.value;
var hidden = document.createElement("input");
form.appendChild(hidden);
hidden.type = "hidden";
hidden.name = "m";
hidden.value = generate_other_value(val);
entry.value = "";
form.submit();
}
But before submitting I want to validate the entry and other elements of the form - I can do that manually ofc. but HTML5 gives us the required and so many other attributes - how can I simply integrate them? Is there something like form.isValid()
? Googling "validate javascript html form" just gives me examples that deal with the manual validation in javascript from "ye olde times" ...
Upvotes: 1
Views: 3254
Reputation: 825
You can use checkValidity
, which is a method provided by HTMLFormElement
. In your example, it would be something like if ( !form.checkValidity() ) { code here }
. From MDN:
[checkValidity] Returns true if all controls that are subject to constraint validation satisfy their constraints, or false if some controls do not satisfy their constraints. Fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled.
As that says, it also fires an invalid
event at every invalid form item. Then you can just make your own handler to show invalidity, like something described in this answer.
Upvotes: 2