Re: email validation
by Andrew McFarland <aamcf(at)aamcf.co.uk>
|
Date: |
Wed, 30 Jan 2002 21:03:57 +0000 |
To: |
hwg-basics(at)hwg.org |
In-Reply-To: |
|
|
todo: View
Thread,
Original
|
|
[Quick disclaimer: the methods described here don't actually validate the
e-mail address; they just check for the presence of some things that mean a
given string is probably an valid e-mail address.]
At 12:34 30/01/02 -0500, Cook, Shelby wrote:
>I'm working on a form validator and currently have this for the email field:
>
>$email = $input{email};
> if ( $email eq "" ) {
> print "You didn't provide your E-mail Address ! <br>\n";
> $err++;
> }
>
>Is there a way to tell it to not only look for a blank field but to also
>look for the @ symbol?
You want to use a regular expression. The precise syntax depends on the
language, but I'm guessing you are using perl.
Something like
if ($email =~ /\w@\w/) {}
Should do the trick. This is true if there is (at least) one word character
(\w) followed by an @ followed by (at least) one word character.
For example,
#! -usr/bin/perl -w
use strict;
use warnings;
my $email = "aamcf\(at)aamcf.co.uk";
print "$email\n";
if ($email =~ /\w@\w/) {
print "foo\n"
}
prints:
aamcf(at)aamcf.co.uk
foo
Although you should always do server side testing of data, client side
testing can be very useful as well. For one thing it saves time when a user
is reminded to enter their e-mail address without the data going to the
server and back again.
Here's a snippet of JavaScript that will check if a field has an e-mail
address:
function checkme(form){
message = '';
if (isEmail(form.email1)) {message += "email1
filled\n"};
if (message) {alert(message); return false}
return true;
}
function isEmail(ele) {
var email = /\w@\w/
return email.test(ele.value)
}
The form tag should have an onsubmit="checkme(this)" to work.
A couple of warnings about the above code. It's more complex than it needs
to be because it is a cut down version of a larger suite of form validation
tools I wrote a while back. It also hasn't been tested very thoroughly (I
can't remember if regular expressions are well supported in JavaScript or not).
If anyone wants to see the rest of the JavaScript I wrote, give me a shout.
If enough people ask I may even write it up and post to the list :-)
Andrew
HTML: hwg-basics mailing list archives,
maintained by Webmasters @ IWA