EN
JavaScript - stop form submission on validation fails
6 points
In this article, we would like to show you how to stop form submission on validation fails using JavaScript.
Quick solution:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
function validateForm(form) {
7
// ... // put some validation conditions here ...
8
return false; // `return false` when we want to stop form submission
9
// `return true` when we want to submit form
10
}
11
12
</script>
13
<form onsubmit="return validateForm(this)">
14
<!-- put some fields here ... -->
15
<button>Submit</button>
16
</form>
17
</body>
18
</html>
In the example below, we handle onsubmit
event, returning false
when validation fails. That approach stops form
submission when it is needed. As example validation, we check if input field has some value.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
function hasValue(form, name) {
7
var field = form.elements.namedItem(name);
8
return field.value.length > 0;
9
}
10
11
function validateForm(form) {
12
var valid = hasValue(form, 'field'); // some example validation here ...
13
if (valid) { // put validation conditions here ...
14
console.log('Validation success!');
15
return true;
16
} else {
17
console.log('Validation failed!');
18
return false;
19
}
20
}
21
22
</script>
23
<form onsubmit="return validateForm(this)">
24
<label>
25
<span>Field:</span>
26
<input type="text" name="field" />
27
</label>
28
<button>Submit</button>
29
</form>
30
</body>
31
</html>