JS
The date validation file dd/mm/aaaa
fails if you put 10 and 20 as days.
The code is this:
function validaEdat(){
vesSumant();
vfalladata = false;
//Comprovació de la data de naixement i el correu electrònic
var vregexNaix = /^([012][1-9]|3[01])(\/)(0[1-9]|1[012])\2(\d{4})$/;
vdataNaix = document.formu.dataNaix.value;
vanyData = vdataNaix.substring(vdataNaix.length-4, 4);
if((!vregexNaix.test(vdataNaix)) || (/^(\d{4})$/.test(vanyData))){
alert("Bonvolu skribi naskighdato per tt/mm/jjjj. \n--------------------------------------\n Per favor, empleneu la data com dd/mm/aaaa.");
document.formu.dataNaix.value = "";
document.formu.dataNaix.focus();
return false;
}
controlaCaselles();
return true;
}
Validate a date
Validating a date with a regular expression, while possible, is impractical and there are very few cases where I would recommend it. For me, the limitation is: Do you understand each part of the regex? Will you understand it easily in a few years? If another developer had to edit your code, could they easily understand it?
There are many simpler alternatives to validating dates:
HTML5 incorporated a new type of
<input>
, Input Type Date (see compatibility !).Use Moment.js , which generates a wrapper for Date (or can even be wrapped in Date).
Convert to Date and see if it keeps the same value.
Use a regex to validate that they are digits, and then manually validate each value.
With jQuery and jQuery UI , using the Datepicker widget . The widget can be displayed, or not. You only need to call the
$.datepicker.parseDate()
. In the example, the date can be entered in the input or in the datepicker. However, input could be disabled so that it is not entered manually. If not, another alternative is to not use an input, and display the datepicker constantly in a div.Use bootstrap-datepicker (similar to above).
RegEx to validate any date m/d/yyyyregex101.com
Validates any date, including February days in leap years.
Code to validate and extract day, month and year (detailed with variables)
Above the previous expression, we use parentheses (groups) to obtain each of the parts:
The problem is in the
RegExp
vregexNaix
, which does not accept neither the10
nor the20
A solution would be to modify said
RegExp
, for example like this:demonstration:
I think the simplest way to validate a date without so much code would be:
Add (
-
) to validate"01-03-1993"
.