This can be achieved by utilizing the
onsubmit
event of forms. The example below illustrates this.<form name='form' action='add' onsubmit='return validateForm()' method='post'>
<label for='name'>Enter your name:</label>
<input id='name' name='name'>
<button type='submit'>Submit</button>
</form>
<script>
function validateForm() {
var input = document.getElementById('name').value;
return /^[A-Z a-z]*$/.test(input);
}
</script>
This simple validation checks that the input contains only alphabets and space. If the validation fails, the form will not be submitted. Unfortunately, the user will be left wondering why isn't anything happening after clicking the submit button. We can do better by adding feedback.
<form name='form' action='add' onsubmit='return validateForm()' method='post'>
<label for='name'>Enter your name:</label>
<input id='name' name='name'>
<button type='submit'>Submit</button>
</form>
<script>
function validateForm() {
var input = document.getElementById('name').value;
if (/^[A-Z a-z]*$/.test(input)) {
alert('Name must be contain only alphabets and/or space.')
return false;
}
return true;
}
</script>
This time, the user will get to see why the form isn't submitting. This may work for forms with one or two input fields, but on long forms a user entering several invalid inputs would be annoyed with the multitude of pop ups. We can do better by adding immediate feedback.
<form name='form' action='add' onsubmit='return validateForm()' method='post'>
<label for='name'>Enter your name:</label>
<input id='name' name='name' onblur='validateName()'>
<span id='namefb'>
<button type='submit'>Submit</button>
</form>
<script>
function validateName() {
var input = document.getElementById('name').value;
var feedback = document.getElementById('namefb');
if (/^[A-Z a-z]*$/.test(input)) {
feedback.innerHTML = 'Name must be contain only alphabets and/or space.';
return false;
}
feedback.innerHTML = '';
return true;
}
function validateForm() {
return validateName();
}
</script>
This example uses the
onblur
event for input elements, which happens when the user navigates to the next field. You can easily extend the examples for your own needs (only practical for the smallest of projects because it quickly becomes tiresome -- after which you should use a library such as this), but remember that any user with JavaScript disabled will not have their inputs validated. Server-side validation is still a must!
No comments:
Post a Comment