I need to validate 2 fields of my form, $nombre
and $apellidos
.
I've been trying this code but it doesn't meet all the conditions I want to apply to validation, including common whitespace in first and last names:
if (!preg_match("/^[a-zA-Z'-]+$/",$nombre)) {
echo "El nombre tiene caracteres inválidos";
}
What I need is the following (The first and last names will use the same validation except for length):
- It should only contain az AZ characters (including the letter Ñ and spaces ).
- A minimum of 3 characters (not counting spaces)
- A maximum of 18 characters in the name and 36 in the surnames.
My code:
// Validar nombre
if (!preg_match("/^[a-zA-Z'-]+$/",$nombre)) {
array_push($errors, "El nombre contiene caracteres inválidos.");
} else if (strlen($firstname) > 18) {
array_push($errors, "El nombre solo puede contener hasta 18 caracteres.");
} else if (strlen($firstname) < 3) {
array_push($errors, "El nombre debe tener al menos 3 caracteres.");
}
// Validar apellidos
if (!preg_match("/^[a-zA-Z'-]+$/",$apellidos)) {
array_push($errors, "Los apellidos contienen caracteres inválidos.");
} else if (strlen($lastname) > 36) {
array_push($errors, "Los apellidos solo pueden contener hasta 36 caracteres.");
} else if (strlen($lastname) < 3) {
array_push($errors, "Los apellidos debe tener al menos 3 caracteres.");
}
As you can see, it is missing the SPACE filter and the letter Ñ. In terms of length, I already have it, only that the minimum of 3 characters would be missing but counting only letters and not spaces for this to be invalid:" "
Note:
array_push($errors, "Mensaje de error.");
$errors
it is an array that stores all the errors and later shows them in the form.
I think I have it:
Name:
/^(?=.{3,18}$)[a-zñA-ZÑ](\s?[a-zñA-ZÑ])*$/
(?=.{3,18}$)
-> checks the length, if it is more than 3 and less than 18 characters[a-zñA-ZÑ]
-> look at the first word and if it meets the rule of being only Alphabetical withñ
included(\s?[a-zñA-ZÑ])
-> in case there is a space, I indicate that there will be another wordThe surname will be the same, but we indicate that the maximum is 36 characters:
^(?=.{3,36}$)[a-zñA-ZÑ](\s?[a-zñA-ZÑ])*$
.Clearly it won't match you if there are 3 spaces at the beginning. Hope this can help you.
Try this example, here I allow all the characters that can be used to form a name and a surname and I validate their length, if you want to know exactly what they failed, let me know to edit the answer