By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,947 Members | 1,505 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,947 IT Pros & Developers. It's quick & easy.

Form validation

P: n/a
DM
I'm a newbie in javascript, and came across this problem:

I have a form with several fields, and I need to validate the form. For each
field that needs validation, I include the following:

-------------------------------------
<tr><td >Email:</td><td><input type="text" name="email" value="$email"
onChange="return ValidateEmail(this);"/></td></tr>
-------------------------------------
function ValidateEmail(entered)
{

var re_email=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/

if(re_email.test(entered.value))
{
}
else {
alert("Invalid email.")
}
}
-----------------------------

It works fine... except: if I enter an invalid email it prompts me with an
error message, and continue (without changing the email address), the
validation is not done again. I tried onBlur instead of onChange, but I get
the same results.

Can anyone suggest how to avoid this problem? Thanks.
Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
> -------------------------------------
function ValidateEmail(entered)
{

var re_email=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/

if(re_email.test(entered.value))
{
}
else {
alert("Invalid email.")
}
}
-----------------------------

It works fine... except: if I enter an invalid email it prompts me with an error message, and continue (without changing the email address), the
validation is not done again. I tried onBlur instead of onChange, but I get the same results.


You have to return a boolean value from the function (true | false)
depending on whether
your email string fits the pattern. You'd also want to set the focus back to
the form element with the problem.

This should give you a structure to start things off.

function ValidateEmail(formelement) {
if (email_is_bad) {
return false;
formelement.focus();
}
else true;
}

Jul 20 '05 #2

P: n/a
JRS: In article <Rg*******************@news20.bellglobal.com>, seen in
news:comp.lang.javascript, DM <dm@nospam.com> posted at Sun, 2 Nov 2003
23:59:28 :-

var re_email=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/

if(re_email.test(entered.value))


That rejects j+*@b.cc which I believe to be a permissible address;
likewise j$*@b.cc

When validating, it is rather important that everything legitimate
should be accepted.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.