Reputation: 20090
Preface, I really don't know javascript at all.
I am trying to validate the email address of a form. If validation fails, I would like to focus on the invalid email field, and show a warning message. The below code properly returns true or false if the "focusElement" line is removed. However, it always returns true with that line included (presumably because the line is invalid and the code does not execute. Is there a proper/simple way of focusing on this element and showing the message?
function validateForm(formElement)
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailPattern.test(formElement.tfEmail.value))
{
return true;
}
else
{
focusElement(formElement.tfEmail,'Please enter a valid e-mail address.');
return false;
}
}
Upvotes: 1
Views: 539
Reputation: 2755
You should try use jQuery and jQuery Validate for this task.
jQuery is the most used JavaScript framework, it can simplify a lot of any tasks in JavaScript.
jQuery Validate is a very used plugin for validation, based on jQuery.
Upvotes: -1
Reputation: 100175
Try:
alert("Ur err msg"); document.getElementById("yourEmailFieldId").focus();
Upvotes: 1
Reputation: 61812
...
else
{
alert('Please enter a valid e-mail address.');
formElement.tfEmail.focus();
return false;
}
If you would like the functionality to be in a separate function like your example:
...
else
{
focusElement(formElement.tfEmail, 'Please enter a valid e-mail address.');
return false;
}
function focusElement(obj, msg)
{
alert(msg);
obj.focus();
}
Upvotes: 2