Reputation: 37
I'm trying to validate what a user enters into a texbox on the client-side, using javascript. I have also added a span close to my input tag like so,
<div>
<label for="fname">First Name*</label>
<input id="fname" name="fname" maxlength="30" type="text" /><span style="display:none;" id="fnameerror" name="fnameerror">*Please enter your firstname</span>
</div>
Here's the javascript code snippet validating the input,
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
}
What I want to achieve now is, 1) The textbox with the error should gain focus. 2) After the error message is displayed and the user enters a valid data, the error message should disappear.
How do I achieve this. I'm fairly new to javascript. Thanks.
Upvotes: 0
Views: 115
Reputation: 1228
If you've read about HTML5, it allows you to add form validation as attribute fields directly instead of having to write code for it. It also presents things neatly. Have a look. This might help: http://diveintohtml5.info/forms.html
Upvotes: 1
Reputation: 7070
Change your JS code:
document.getElementById('fname').onkeyup = function() {
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
document.getElementById('fname').focus();
} else {
valid=true;
document.getElementById('fnameerror').style.display='none';
}
}
Upvotes: 2
Reputation: 3372
I will suggest to use Jquery validator. Of course you need to include jquery,and jquery plugin, but you do not need time to write validation from the scratch only to implement what exist.
Upvotes: 0