I leave my script to help me understand where the error is and to be able to correct it:
#!/bin/bash
fechaDeNacimientoRegex='^19|20[0-9]{2}[1-12]{2}[1-31]$'
#Validacion y entrada de la fecha
read -p "Por favor ingresa la fecha formato [yyyyMMdd]:
" fechaNacimiento
if [[ $fechaNacimiento =~ $fechaDeNacimientoRegex ]]; then
echo "La fecha $fechaNacimiento es valida"
else
echo "La fecha $fechaNacimiento es invalida"
fi
The output when I enter a date between 1900 and 1999 works:
Por favor ingresa la fecha formato [yyyyMMdd]:
19921129
La fecha 19921129 es valida
But it doesn't work when I put 2000 or greater:
Por favor ingresa la fecha formato [yyyyMMdd]:
20110330
La fecha 20110330 es invalida
If you want to validate a date, what better than to use
date
same to validate it. If you pass it withdate -d "$fecha"
, the exit code will tell you if it's good or not:Let's see it with a couple of examples:
As I said in a comment, the regular expression is wrong. You can't just say you want numbers between 1 and 12, you can say which characters to accept and in what order.
I have a regular expression, rather longer, but which seems to work for what you want:
Part by part:
(19[0-9]{2}|20[0-9]{2})
This is similar to what you have, but in parentheses to capture it.(0[1-9]|10|11|12)
means a 0 followed by a number between 1 and 9, or a 10, or an 11, or a 12. Between parentheses to capture the result.(0[1-9]|1[0-9]|2[0-9]|3[0-1])
means a 0 followed by a number between 1 and 9, or a 1 followed by a number between 0 and 9, or a 2 followed by a number between 0 and 9, or a 3 followed by a 0 or 1. Enter parentheses to capture the result.Thanks to capturing the result, we can do:
Now, the variables
$anio
,$mes
and$dia
contain the part that matches the regular expression, and you can do more validations, for example, that February does not accept more than 29 days, or indicate which number makes the date invalid:It sounds like that regular expression would be extremely verbose.
I propose an alternative with a perl type regex and
grep
:Now with an invalid:
Used in your code, it would look something like this:
You could also do an analysis by number. That is, by the first four numbers that are between "1900" and "2099". And the following that belong to a regular expression.