Reputation: 51
I currently have the following working code but I need to build on to this some email and phone number validation to make sure it is an actual email and phone number not other data. I have found code to use
function valid_email($email) {
return !!filter_var($email, FILTER_VALIDATE_EMAIL);
}
but I'm unsure how to incorporate this into my current code. I would love some help with this.
This is my current php code
//load form validate
$firstName= $_POST['firstName'];
$lastName= $_POST['lastName'];
$address = $_POST['address'];
$phoneNumber = $_POST['phoneNumber'];
$email= $_POST['email'];
$username= $_POST['username'];
$password = sha1 ($_POST['password']);
$role = 1;
//prepare input data in an array
$userdata = array($firstName, $lastName, $address, $phoneNumber, $email, $username, $password,$role);
//prepare error list
$errors = array ();
//Validation tests and store list
if ($firstName == "" || $lastName == "" ||
$address == "" || $phoneNumber == "" ||
$email == "" || $username == "" ||
$password == "" || $role == "" ) {
array_push($errors, "All form fields must be filled out before submitting.");
}
//if errors redirect back to form page and save attempted data.
if (count($errors) > 0) {
$_SESSION['userdata'] = $userdata;
$_SESSION['errors'] = $errors;
header("Location: ../register.php");
}else{
unset($_SESSION['userdata']);
unset($_SESSION['errors']);
$query = "INSERT INTO customers (firstName, lastName, address, phoneNumber, email, username, password) VALUES ('$firstName','$lastName', '$address', '$phoneNumber', '$email', '$username', '$password')";
//die (print_r($query));
if (mysqli_query($mysqli, $query)) {
$last_id = $mysqli->insert_id;
$query2 = "INSERT INTO users_in_roles (userID, roleID) VALUES ('$last_id', 1);";
if ($mysqli->query($query2)) {
header("Location: ../Login.php");
}else {
die(print_r($mysqli->error));
}
}
}
Upvotes: 2
Views: 7781
Reputation: 23958
This is one example.
I made a foreach with an array just to show you both outputs.
$email = ["[email protected]","abc@gmailcom"];
foreach ($email as $e){
if (filter_var($e, FILTER_VALIDATE_EMAIL)) {
echo "valid";
} else {
echo "not valid";
}
}
In your case you should probably have it after you check if any of the fields are empty:
if ($firstName == "" || $lastName == "" ||
$address == "" || $phoneNumber == "" ||
$email == "" || $username == "" ||
$password == "" || $role == "" ) {
array_push($errors, "All form fields must be filled out before submitting.");
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
array_push($errors, "Email is not valid.");
}
$phone = "11-331-11111";
$phone = preg_replace("/[^\d]/", "", $phone);
if (strlen($phone) <= 10) {
array_push($errors, "Phone not valid.");
}
Removes non digits and checks if length is less than or equal to 10.
Upvotes: 4