Reputation: 311
I have been searching for hours trying to find a way to validate my form while the user is typing. for example, I want have a field for zip code. I want the user to see a message underneath the field that says they have gone beyond the limit of characters for this field but before they submit the form. How can this be done?
with such code:
<form method="POST" name="wrriregistration" target="_blank"><center>
<table width="100%">
<tbody>
<tr>
<td width="149"><strong>*First Name:</strong></td>
<td width="229"><input type="text" name="first_name" size="35" maxlength="100"/></td>
<td width="123"><strong style="display:none;">Middle Initial:</strong></td>
<td width="659"><input style="display:none;" type="text" name="middle_initial" size="35" maxlength="50" /></td>
</tr>
</tbody>
</table>
</form>
Upvotes: 0
Views: 733
Reputation:
Try this :
HTML
<input type="text" name="first_name">
<div id="error">
My custom error
</div>
CSS
#error {
display: none;
}
#error.show {
display: block;
}
input {
color: #000000;
}
.invalid {
color: #FF0000;
}
JS
var input = document.querySelector('[name="first_name"]');
var error = document.getElementById('error');
input.addEventListener('keydown', function(){
// Whatever you want
if(this.value.length >= 10) {
this.classList.add('invalid');
// You can control style of your invalid input with .invalid
error.classList.add('show'); // Display your custom error
} else {
this.classList.remove('invalid');
error.classList.remove('show');
}
});
EDIT Explanation :
var input
target your first_name input
addEventListener
makes a event detection. Passed with argument 'keydown', JavaScript will listen to keys pressed.
classList
is an API to manipulate classes (not supported by IE).
Try it here : https://jsfiddle.net/e3oe4ykf/
Upvotes: 2