i have encountered a problem with php server side validation. I am trying to validate the password field which should follow the following rules: between 8 and 15 symbols, at least 1 uppercase, at least 1 special symbol, at least 3 letters and at least 2 numbers. Every validation passes except for the password one and i can't figure out why. My php code is:
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.");
}
}