I have a button that submits a form, but I also want it to link to another page. I only want it to link to the next page if all of the fields in the form are filled in (all fields are required). I'm thinking this will involve JavaScript, which is fine, but I'd like to avoid jQuery. Thanks.
-
http://www.w3schools.com/js/js_validation.asp – Vladimir M Nov 27 '16 at 15:21
2 Answers
The way to usually do it, is combine normal form submission with POST
-Redirect-GET
(the server accepts the form submission, then redirects the page).
With normal form submission, all you need to do is mark the fields as required
like so:
<form method="post" action="/what/ever">
<label>Name: <input required></label>
<label>Email: <input type="email" required></label>
<input type="submit" value="Send">
</form>
After the form submission is successful, redirect the page from the server-side to the next page (or to an error page, in case something went wrong).

- 172,118
- 50
- 264
- 308
Form validation can easily be done client side by using the HTML5 required
field.
<input type="text" required />
However, all browsers doesn't support HTML5 and for those you can use a JavaScript based solution. This can be implemented in an infinite number of ways. For example by adding an event listener on the submit button, verifying that all fields are non-empty and otherwise preventing the submission.
var form = document.forms["form-name"];
var formFields = form.getElementsByTagName("input");
form.addEventListener("submit", function (event) {
var validationOk = true;
for (var i = 0; i < formFields.length; i++) {
if (formFields[i].value == "") {
validationOk = false;
// Here you probably also want to give the user some kind
// of feedback by adding a class to the field or similar
}
}
if (!validationOk) {
event.preventDefault();
}
});
However, note that from a security perspective, you should never trust client side validation, but rather do it server side as long as the validation isn't only for the sake of improving the user experience.

- 38
- 4