I am wondering if anyone out there can help with my form Validation Please?
I am having a few problems trying to synchronized out how certain bits of the actual structure of the script works together.
<?php
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])){
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
}
else{
$msg=$msg."Your Key is valid!<BR>";
$flag="OK";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
$flag="OK";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
}else{ // all entries are correct and let us proceed with the database checking etc …
}
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['email']))
{//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
}
?>
the problem, when email valid, password valid, though key is invalid the warning of key disappear, it mean passed too... and also the spamcheck doesn't look work..
You don't have to set the flag to 'OK' or a previous error get masked, as you already noted.
If all the check are ok, the flag remains in valid state and you can pass on, otherwise, if one of the check fails the flag reports the incorrect state.
$flag="OK"; // This is the flag and we set it to OK
$msg=""; // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$msg=$msg."Your Key not valid! Please try again!<BR>";
$flag="NOTOK";
} else {
$msg=$msg."Your Key is valid!<BR>";
}
}
$email=$_POST['email'];
echo "Your Email: ".$email." is";
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$msg=$msg."Invalid email<BR>";
$flag="NOTOK";
}else{
$msg=$msg."Valid Email<BR>";
}
$password=$_POST['password'];
if(strlen($password) < 5 ){
$msg=$msg."( Please enter password of more than 5 character length )<BR>";
$flag="NOTOK";
}
if($flag <>"OK"){
echo "$msg <br> <input type='button' value='Retry' onClick='history.go(-1)'>";
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Said that I would use a different approach, for example using boolean values other than a string named flag. You can obtain a more fluent code calling it something like $inputIsvalid.
Other nags: Sometimes you add the messages to a $msg variable, other you issue an echo, maybe it is an oversight.
There is a lot of room for improvements, as every other code, I will address just some of the easy issues, for examples I will not check if the variables are set or not.
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(isset($_POST['Send'])) {
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
if($key!=$num_key){
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
} else {
$messages[]'Your Key is valid!';
}
}
$email=$_POST['email'];
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
$emailIsValid = eregi($emailRegEx, $email);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=$_POST['password'];
if(strlen($password) < 5 ){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Another approach should be (the functions are quite simple, but you can modify the validation policy of the different components without affecting the main code):
function validateKey() {
if(!isset($_POST['Send'])) {
return true;
}
$key=substr($_SESSION['key'],0,4);
$num_key = $_POST['num_key'];
return $key==$num_key;
}
function validateEmail($email) {
$emailRegex='^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$';
return eregi($emailRegEx, $email);
}
function validatePassword($password) {
return strlen($password) < 5;
}
$inputIsValid=true; // This is the flag and we set it to OK
$messages = array(); // Initializing the message to hold the error messages
if(validateKey()) {
$messages[]'Your Key is valid!';
} else {
$messages[]= 'Your Key not valid! Please try again!';
$inputIsValid=false;
}
$emailIsValid = validateEmail($_POST['email']);
$messages[]= 'Your Email: '.$email.' is ' .($emailIsValid? 'Valid':'Invalid');
$inputIsValid = $inputIsValid && emailIsValid;
$password=;
if(!validatePassword($_POST['password']){
$messages[]='( Please enter password of more than 5 character length )';
$inputIsValid=false;
}
if(!inputIsValid){
$messages[]='<input type='button' value='Retry' onClick='history.go(-1)'>';
echo join('<br/>', $messages);
} else {
// all entries are correct and let us proceed with the database checking etc …
}
Spam function:
why are you using Constant different than the boolena values?
(TRUE is different from true and FALSE is different from false)
You can rewrite the function like this in order to obtain the desired behaviour.
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
return filter_var($field, FILTER_VALIDATE_EMAIL);
}
if (isset($_POST['email'])) {//if "email" is filled out, proceed
$mailcheck = spamcheck($_POST['email']);
if (!$mailcheck) {
echo "Invalid input";
}
}
Each of you tests sets flag to "OK" or "NOTOK" overwriting decisions made by previous tests.
You could start with $flag = true;. And only if a test decides that the input is unsatisfying it sets $flag=false.
Or you can remove $flag altogether and check if 0===strlen($msg) after the tests.
Related
I am asking for an email address through a form in my website. I want to validate the domain so that I can prevent fake entries I am getting right now. I am using the following code, but it dose not seem to work :
function myCheckDNSRR($hostName, $recType = '')
{
if(!empty($hostName)) {
if( $recType == '' ) $recType = "MX";
exec("nslookup -type=$recType $hostName", $result);
// check each line to find the one that starts with the host
// name. If it exists then the function succeeded.
foreach ($result as $line) {
if(eregi("^$hostName",$line)) {
echo "valid email";
}
}
// otherwise there was no mail handler for the domain
echo "invalid email";
}
echo "invalid EMAIL";
}
I am new to this and used this code from here
Please guide me. Thanks.
I guess you can simply ping like this.
function myCheckDNSRR($email_address)
{
if(!empty($email_address)) {
$hostName=strstr($email_address, '#');
$hostName=str_replace("#","www.",$hostName);
exec("ping " . $hostName, $output, $result);
if ($result == 0){
echo "valid email";
}
else{
echo "invalid email";
}
}
}
call it like
echo myCheckDNSRR("sample#gmail.com");
Use a validation lib like https://docs.zendframework.com/zend-validator/validators/email-address/
$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
Create a table in your DB for storing an email link code. When someone registers, mark the user as unactivated until he clicks the link in the email. This way, you know it's real, and can activate the user.
I have a fairly straight-forward validation system on my registration page within my website. It all works fine, however, it seems unnecessarily messy; with always checking if a variable ($regOpen) is true, and then setting a variable ($errors) to true each time there is an error.
This is the very simplified script and relative HTML:
<?php
$regOpen = false;
$errors = false;
if(Input::is("register")){ // if a user has clicked register
$regOpen = true;
}
if($regOpen){ // checking if input is set first time
if(Input::empty("email")){
echo '<span>Your email address must not be left blank.</span>';
$errors = true; // setting to true for the first time
}
if($email->exists()){
echo '<span>A user with that email already exists.</span>';
$errors = true; // 2nd
}
if(!filter_var(Input::get("email"), FILTER_VALIDATE_EMAIL)){
echo '<span>That is not a valid email type.</span>';
$errors = true; // 3rd
}
}
?>
<input type="text" name="email">
<?php
if($regOpen){ // 2nd
if(Input::empty("password")){
echo '<span>Your password must not be left blank.</span>';
$errors = true; // 4th
}
if(strlen(Input::get("password")) < 4){
echo '<span>Your password must be a minimum of 4 characters.</span>';
$errors = true; // 5th
}
}
?>
<input type="password" name="password">
<?php
if($errors){ // if there are errors
echo '<span>Registration failed.</span>';
} else {
// register user
echo '<span>Registration successful.</span>;
}
?>
In reality, I actually have about several fields I need to check (each with their own list of errors to check), so as you can imagine; checking and setting all these variables seems a bit tedious and unnecessary.
What I want to know is, if there is a way to only have to set the $errors variable to true, once. Not only that, if there is a way to reduce the way I check if $regOpen is true (instead of checking each time I need to check for errors).
Thanks.
You could use $errors as an array for errors instead of being just an indicator. Then you could check if $errors array is not empty, then it contains errors.
Here's a clearer version of your code:
<?php
function print_errors($errors) {
foreach($errors as $error) {
echo '<span>' . $error . '</span>';
}
}
$regOpen = Input::is("register");
$errors = [];
if($regOpen){ // checking if input is set first time
if(Input::empty("email")){
$errors['email'][] = "Your email address must not be left blank.";
}
if($email->exists()){
$errors['email'][] = "A user with that email already exists.";
}
if(!filter_var(Input::get("email"), FILTER_VALIDATE_EMAIL)){
$errors['email'][] = "That is not a valid email type.";
}
if(Input::empty("password")){
$errors['password'][] = "Your password must not be left blank.";
}
if(strlen(Input::get("password")) < 4){
$errors['password'][] = "Your password must be a minimum of 4 characters.";
}
}
?>
<?php isset($errors['email']) ? print_errors($errors['email']) : null; ?>
<input type="text" name="email">
<?php isset($errors['password']) ? print_errors($errors['password']) : null; ?>
<input type="password" name="password">
<?php
if(count($errors) > 0){ // if there are errors
echo '<span>Registration failed.</span>';
} else {
// register user
echo '<span>Registration successful.</span>';
}
?>
You may now get the idea.
First of all, many of the checking are not necessary at PHP level, you can use the HTML 5 form validation for many cases. Secondly, for a few case that HTML5 form validation can't handle, you don't need to purposely set $errors=true, you could do something like $error=$email->exists();.
Basically this is my registration form. I want to make it so if all the fields are not filled in it will give an error. What do I do from here? I would also like to display the error as $msg
<?php
include'db.php';
$msg='';
if (empty($_POST[''])
|| empty($_POST['password'])
|| empty($_POST['repassword'])
|| empty($_POST['user_firstname'])
|| empty($_POST['user_lastname'])
){
// details sent Form
$company=mysql_real_escape_string($_POST['company']);
$address=mysql_real_escape_string($_POST['address']);
$email=mysql_real_escape_string($_POST['email']);
$phone=mysql_real_escape_string($_POST['phone']);
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/'; //this defines what a valid email should be
if(preg_match($regex, $email))
{
$activation=md5($email.time()); // Encrypted email+timestamp, so randomly generated and unique
$count=mysql_query("SELECT uid FROM preciousmetals WHERE email='$email'") or die(mysql_error());
if(mysql_num_rows($count) < 1)
{
mysql_query("INSERT INTO preciousmetals(company,address,email,phone,activation) VALUES('$company','$address','$email','$phone','$activation');");
// sending email
include 'smtp/Send_Mail.php';
$to=$email;
$subject="Email verification";
$body='Hello, we need to make sure you are human. Please verify your email and get started using your Website account. '.$base_url.''.$activation.'';
Mail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= '<font color="#cc0000">This email is already in use, please enter a different one.</font>';
}
}
else
{
$msg = '<font color="#cc0000">The email you have entered is invalid, please try again. </font>';
}
}
?>
Thank you for helping out!
Simply do
if (empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])){
$msg = 'You have not filled all fiels';
} else {
// details sent Form
......
}
echo $msg;
And also check for filter_var() for email validation its much more nicer than regEx
http://php.net/manual/en/filter.examples.validation.php
I'm currently working on a registration system and ran into some problem.
I'll start with pasting a simplified version of the code before:
session_start();
if (isset($_SESSION['logged_in'])) {
header('Location: #notLoggedIn');
exit;
} else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if //if field is empty {
//display error
} else if //check if any unallowed characters {
//display another error
} else {
//give the checked input a string/variable, ex: $name= ($_POST["name"]);
}
// Like 4-5 other checks running in the same way as above
}
$query = $pdo->prepare('INSERT INTO table (a, b, c, d, e) VALUES (?,?,?,?,?)');
$query->bindValue(1, $1);
$query->bindValue(2, $2);
$query->bindValue(3, $3);
$query->bindValue(4, $4);
$query->bindValue(5, $5);
$query->execute();
header('Location: index.php');
exit;
}
The problem is the fact that it runs everything at once and just redirects me to index.php.
How do I make sure it first of all checks if the form has been submitted before running.
After that I want it to check for any errors in ALL fields. If there are errors, stop.
But if there are no errors, just continue on and upload to my database.
I do think that I'm on a goodway, but currently pretty stuck, any help or push in the correct direction would be awesome!
Thank you!
Your question isn't exactly clear, nor is your code which is also incomplete (where is the form?).
You seem to be at an early stage of learning the form handling, and likely would benefit from further reading and testing before you ask specific questions.
Here are some starters:
http://en.wikipedia.org/wiki/Post/Redirect/Get
What's the best method for sanitizing user input with PHP?
The definitive guide to form-based website authentication
I'll give some info anyway, as have some free time.
For example, your first if checks if session IS set, if TRUE redirect to notLoggedIn. Are you sure this is intentional? Either they're logged in, echo message to suit, or not and so show the reg page (most sites show a login and reg on the same page, for convenience for all scenarios).
As this is a registration form, surely you meant if IS logged in then redirect to YouAreAlreadyLoggedIn?
In fact, I'd just exit a message "You are already logged in" then stop the script.
The problem is the fact that it runs everything at once and just redirects me to index.php.
That's because it has no other option, as at the end of your script after XYZ it redirects to index.php.
If you do not want it to do this then change it. Either don't redirect, handle the entire process more constructively, or exit at some point you need it to (like form errors).
How do I make sure it first of all checks if the form has been submitted before running.
I don't see a form, so don't know exactly what you are doing to advise.
Ideally you'd use the PRG (Post Redirect Get).
http://en.wikipedia.org/wiki/Post/Redirect/Get
Your Script
I've edited your script to make this an answer to the question, and tidied it up a little.
e.g. in your script, specifically at the top, you don't need the else as there's an exit() in the if. When the if returns true, the script will stop, otherwise (with or without an else) it will continue.
The code:
session_start();
if (isset($_SESSION['logged_in']))
{
exit('You are already logged in');
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if ( strlen($POST['field_name']) < 4 )
{
exit('Minimum 4 chars required');
}
elseif ( strlen($POST['field_name']) > 20 )
{
exit('Max of 20 chars allowed');
}
elseif ( preg_match("/^[A-z0-9]+$/", $POST['field_name']) != 1 )
{
exit('Invalid chars - allowed A-z and 0-9 only');
}
else
{
// Not sure what you want here
// If all ok (no errors above)
// then sanatise the data and insert into DB
}
}
As for entering into the DB, you need much more checking and handling of the entire process before you just allow the DB stuff to run.
Not sure why you redirect to index.php. You'd then need to handle form submission results in index.php to tell user you are registered.
On the form page, tell them the errors they have in the fields, or echo out the success message and what happens next (i.e. go to your account page, or (hopefully) confirm the email you sent before logging in).
As for the validation checks in the POSTed form data, it's entirely up to you what you need. But I've given you some very basic to go on. Make sure your max set in the form matches the database column allowance, or if (eg) DB varchar is set to 15 and you allow users to enter 20, the data they enter will be truncated, and they'll register, but never be able to login (or some other data will be broken, their name/username etc).
got bored. this is not for internet points.
<?php
// create table user (userid int auto_increment primary key, username varchar(60), password varchar(60));
// alter table user add constraint uc_user_username unique (username);
var_dump($_POST);
$user = isset($_POST['username']) ? trim($_POST['username']) : '';
$pass = isset($_POST['password']) ? trim($_POST['password']) : '';
$pass2 = isset($_POST['confirm']) ? trim($_POST['password2']) : '';
$action = isset($_POST['action_type']) ? $_POST['action_type'] : '';
if (empty($_POST)) {
// nothing posted
}
else {
if (empty($user)) {
error('you did not provide a username');
}
elseif (empty($pass)) {
error('you did not provide a password');
}
else {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
if ($action=='new_user') {
$userdata = get_user_info($mysqli,$user);
if ($userdata) {
error('user already exists');
}
else {
$validpass = validate_password($pass);
if ($validpass && $pass==$pass2){
if (make_new_user($mysqli,$user,$pass)) {
print "<br/>new user created<br/><br/>";
}
}
else error('passwords did not match');
}
}
elseif ($action=='login_user') {
$verified = verify_credentials($mysqli,$user,$pass);
if ($verified) {
print "<br/>user logged in<br/><br/>";
}
}
elseif ($action=='update_pass') {
$verified = verify_credentials($mysqli,$user,$pass);
$validpass = validate_password($pass);
if ($verified && $validpass && $pass!=$pass2) {
if (update_password($mysqli,$user,$pass,$pass2)) {
print "<br/>new user created<br/><br/>";
}
}
else error('cannot update to same password');
}
$mysqli->close();
}
}
function error($message) {
print "<br/>$message<br/><br/>";
}
function update_password($mysqli,$user,$pass,$pass2) {
$hash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('update user set password = ? where username = ?');
$stmt->bind_param('ss',$user,$hash);
$stmt->execute();
$msql_error = $mysqli->error;
$updated = !(empty($msql_error));
error($msql_error); // for debugging only
return $updated;
}
function make_new_user($mysqli,$user,$pass) {
$userid = false;
$hash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('insert into user (username,password) values (?,?)');
$stmt->bind_param('ss',$user,$hash);
$stmt->execute();
$msql_error = $mysqli->error;
if (empty($msql_error)) {
$userid = $mysqli->insert_id;
}
else error($msql_error); // for debugging only
return $userid;
}
// really, this should be done with javascript instantaneously
function validate_password($pass) {
$error = false;
if (strlen($pass) < 8) {
error('please enter a password with at least 8 characters');
}
elseif (!preg_match('`[A-Z]`', $pass)) {
error('please enter at least 1 capital letter');
}
else $error = true;
return $error;
}
function verify_credentials($mysqli,$user,$pass) {
$row = get_user_info($mysqli,$user);
$verified = false;
if ($row) {
if (password_verify($pass, $row['pass'])) {
$verified = true;
}
}
else error('username and password did not match');
return $verified;
}
function get_user_info($mysqli,$user) {
$row = array();
$stmt = $mysqli->prepare('select userid, username, password
from user
where username = ?');
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->bind_result($row['userid'],$row['user'],$row['pass']);
if (!$stmt->fetch()) $row = false;
$stmt->close();
return $row;
}
?>
<body>
<form action='?' method='post'>
<table id='input_table'>
<tr><td><span>username </span></td><td><input id='username' name='username' type='text' value='<?php echo $user ?>'></td></tr>
<tr><td><span>password </span></td><td><input id='password' name='password' type='text' value='<?php echo $pass ?>'></td></tr>
<tr><td><span>password2</span></td><td><input id='password2' name='password2' type='text' value='<?php echo $pass2 ?>'></td></tr>
<tr><td> </td><td> </td></tr>
<tr><td colspan=2>this just picks the action for testing... you wouldn't keep it around</td></tr>
<tr><td><input type='radio' name='action_type' value='new_user' <?php echo $action=='new_user'?'checked':'' ?>>New User</td></tr>
<tr><td><input type='radio' name='action_type' value='login_user' <?php echo $action=='login_user'?'checked':'' ?>>Logging In</td></tr>
<tr><td><input type='radio' name='action_type' value='update_pass' <?php echo $action=='update_pass'?'checked':'' ?>>New Password</td></tr>
<tr><td> </td><td> </td></tr>
<tr><td colspan=2><input id='submit' name='submit' type='submit'/></td></tr>
</form>
</body>
// error = 0 means no error found you can continue to upload...
if ($_FILES['file']['error'] == 0) {
}
Here are all of the errors explained: http://php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the
upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the
MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file
upload. PHP does not provide a way to ascertain which extension caused
the file upload to stop; examining the list of loaded extensions with
phpinfo() may help. Introduced in PHP 5.2.0.
To validate input fields
if(empty($_POST['name'])&&empty($_POST['password'])){
//fields empty show error here
}else if (is_numeric($username[0])){
echo 'First character must be a letter';
}
else if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
echo 'Only letters and numbers are allowed';
}else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}else if(!preg_match("/^[\pL\s,.'-]+$/u", $name)) {
echo 'Invalid name.';
}
Im new in php and this should be a easy to make, but I dont now how.
I want to check does $address has characters "#" and "."
<?php
function testEmail($address){
$a = strpos("/#/", $address);
$b = strpos("/./", $address);
if (($a != false) && ($b != false)) {
echo "Email is OK";
} else {
echo "Email is NOT OK";
}
}
testEmail("testmail#gmail.com");
?>
You can simply use filter_var to check validity of email.
$email = 'gaurang#gmail.com'
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Email correct
}
else {
//Email not correct
}
Is your question about this specific piece of code? Then #wroniasty's answer is correct.
But you really don't want to use a regex to test email validity, unless you want to use monstrosities like these.
However, if your question really is "How can I validate an email address?", then take a look at filter_var().
You can pass it the filter FILTER_VALIDATE_EMAIL, so it will validate the email address catching quite a bit of edge cases.
You can check an address using the following code:
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// valid email
} else {
// invalid email
}
<?php
function testEmail($address) {
if (preg_match ( "/\.|#/", $address))
echo "Email OK";
else
echo "Email not OK";
}
?>
a better way to check for valid email address:
<?
function isValidEmail($email){
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
?>