php电子邮件和电话号码验证

时间:2017-11-22 08:33:04

标签: php validation email numbers

我目前有以下工作代码,但我需要建立一些电子邮件和电话号码验证,以确保它是一个实际的电子邮件和电话号码而不是其他数据。我找到了要使用的代码

function valid_email($email) {
    return !!filter_var($email, FILTER_VALIDATE_EMAIL);
}

但我不确定如何将其合并到我当前的代码中。我希望得到一些帮助。

这是我目前的PHP代码

//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));
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这是一个例子 我用一个数组做了一个foreach,只是为了向你显示两个输出。

$email = ["abc@gmail.com","abc@gmailcom"];
Foreach($email as $e){
    If(filter_var($e, FILTER_VALIDATE_EMAIL)){
        Echo "valid";
    }Else{
        Echo "not valid";
    }
}

https://3v4l.org/GcKRp

在您的情况下,在检查是否有任何字段为空之后,您应该可以使用它:

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.");
}

删除非数字并检查lenght是否为10。

抱歉抱歉不是10,小于或等于10。