PDA

View Full Version : php check if fields are empty and valid email.


Tjobbe
November 30th, 2004, 20:23
I know that to check for a valid email address, I have to create a new function, such as:

function isValidEmail ($emailaddy) {
return eregi("^[a-z0-9_]+@[a-z0-9\-]+\.[a-z0-9\-\.]+$", $emailaddy);


where emailaddy is the field the user enters their email address.

I'm just not sure, throguh having watched a VTC php tutorial, where I should include it on my registration.php script, im just a bit confused there.

Also, I want to make sure that certain fields are filled in, and currently it only checks if only one of the the following two fields are empty:

else if ($user || $pass) {
// if the user has filled in one field but not the other,
// throw up this error
echo "Please fill in all fields.";
}

I want it to check a few fields. $emailaddy, $user, $pass and $phonenum

I am assuming I do this:

if (!$user, !$pass, !$phonenum, !$emailaddy){

echo "Please fill in all the required fields.";

but I get this:

Parse error: parse error, unexpected ',' in C:\xampp\htdocs\php\login\register.php on line 47 which is the line i just wrote!

If anyone can point me onto the right track i'd be most greatful!

sonicgroup
November 30th, 2004, 21:03
Rather than commas, use the OR symbol ( || ) - that's two pipes (shift+backslash).

if (!$user || !$pass || !$phonenum || !$emailaddy) {
...;
}

Tjobbe
November 30th, 2004, 21:16
excellent, thank you.

sonicgroup
November 30th, 2004, 21:31
That's assuming that any one field being empty will trigger it. If you want to get more in depth, you could do something of this nature:

[syntax:11f4f12cb2="php"]
//Assign all the field values to an array
$subs['field1'] = $_POST['field1'];
$subs['field2'] = $_POST['field2'];
// ... etc.

$err = 0;
foreach ($subs AS $val) {
if ($val == '') {
$err++;
}
if ($err > 0) {
echo 'Please fill out...';
}

//Taking the above one step further would produce something like this...
$subs = new array ('field1' => $_POST['field1'],
'field2' => $_POST['field2']);
// ... etc.

//Define more user-friendly field names
$fields = new array('field1' => 'field 1 description',
'field2' => 'field 2 description');

$err = ''; // $err is a string this time, versus an integer

// Since we've defined the field descriptions, we can provide
// more useful error messages - i.e. highlight each field that is not
// filled in.
foreach ($subs AS $key=>$val) {
if ($val == '') {
$err .= 'Field '.$fields[$key].' must be filled in.'."\n";
}
if (!empty($err)) {
echo $err;
}
[/syntax:11f4f12cb2]

The output of the second part might look something like this:

Field field 1 description must be filled in.
Field field 2 description must be filled in.