I think this is what you want:
Instead of validating all inputs onblur, just validate the one that left focus. To do that I have passed in the element to Validate(this)
in the HTML inline code. You also had some element ID issues (e.g. no message field). I also added a .focus()
call to keep the input in focus if it's invalid.
function Validate(elem) {
// create array containing textbox elements
var input = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email1'), document.getElementById('email2'), document.getElementById('message')];
for (var i = 0; i < input.length; i++)
// loop through each element to see if value is empty
{
if (input[i].value == '' && elem.id == input[i].id) {
switch (input[i].id) {
case 'fname':
alert('enter you first name');
break;
case 'lname':
alert('enter your last name');
break;
case 'email1':
alert('enter your email address');
break;
case 'email2':
alert('enter your email address');
break;
case 'message':
alert('write your message');
break;
}
elem.focus();
}
}
}
I have to say though that lots of alert()
's are pretty nasty, it would be much better if you show a span next to each textbox with the error message instead.