我遇到了php服务器端验证的问题。我正在尝试验证密码字段,该字段应遵循以下规则:8到15个符号,至少1个大写,至少1个特殊符号,至少3个字母和至少2个数字。每个验证通过除了密码一,我无法弄清楚原因。我的PHP代码是:
if (isset($_POST['register'])) {
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$confirmPass = $form['confirmPass'];
$firstName = $form['firstName'];
$lastName = $form['lastName'];
$address = $form['address'];
$email = $form['email'];
$age = $form['age'];
$phone = $form['phone'];
//Retrieve the field values from our registration form.
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$password = !empty($_POST['password']) ? trim($_POST['password']) : null;
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Validations username
if (strlen($username) < 4 || strlen($username) > 8 || empty($username)) {
throw new Exception("User name must be between 4 an 8 symbols.");
}
$patern = '#^[A-Za-z0-9]+$#';
if (!preg_match($patern, $username)) {
throw new Exception("User name must not contains Special characters.");
}
//Validation password
if (strlen($password) < 8 || strlen($password) > 15 || empty($password)) {
throw new Exception("Password must be between 8 an 15 symbols.");
}
$patern = '#^(?=(.*\d){2,})(?=.*[A-Z]{1,})(?=.*[a-zA-Z]{2,})(?=.*[!@~#$%^&?]{1,})[0-9a-zA-Z!@~#?$^%&`]+$#';
if (!preg_match($patern, $password)) {
throw new Exception("Password must contains at least 1 special symbol at least 1 uppercase letter at least 2 numbers at least 3 letters.");
}
if ($password != $confirmPass) {
throw new Exception("Password do not match.");
}
//Validation email
$patern = '#^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$#';
if (!preg_match($patern, $email)) {
throw new Exception("Please fill valid email.");
}
//Validation phone
if (strlen($phone) != 10) {
throw new Exception("Phone must be 10 numbers.");
}
//Validation age
if (intval($age) < 18) {
throw new Exception("You must be at least 18 years old");
}
//Validation check
if (!isset($_POST['gdpr'])) {
throw new Exception("You must agree with GDPR.");
}
if (!isset($_POST['agreement'])) {
throw new Exception("You must agree with the terms and conditions.");
}
}
答案 0 :(得分:0)
#as delimeter和#在正则表达式的内容中导致过早的结束分隔符因此修饰符错误。
而不是#use /而不是用作成功preg_match()的分隔符而不修改正则表达式的内容。
喜欢来自:
$patern = '#^(?=(.*\d){2,})(?=.*[A-Z]{1,})(?=.*[a-zA-Z]{2,})(?=.*[!@~#$%^&?]{1,})[0-9a-zA-Z!@~#?$^%&`]+$#';
要强>
$patern = '/^(?=(.*\d){2,})(?=.*[A-Z]{1,})(?=.*[a-zA-Z]{2,})(?=.*[!@~#$%^&?]{1,})[0-9a-zA-Z!@~#?$^%&`]+$/';