I need to check the data format in dd-mm-yyyy format.
I'm using the following:
if (ValidateDate() == false) {
alert("Wrong Date Format");
return false;
}
function ValidateDate() {
var dtValue = $('#txtEnteredStartDate').val();
var dtRegex = new RegExp("^(([1-9]|0[1-9]|1[0-9]|2[1-9]|3[0-1])[-]([JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC])[-](d{4}))$");
return dtRegex.test(dtValue);
}
But when I enter dd-mmm-yyyy in the field, for example 19-Nov-2015, I'm getting the error Wrong date format
What am I doing wrong?
PhilVarg's regex is correct, though applying it in RegExp you need to \\ the d.
Also, you can re-factor the ([1-9]|0[1-9]|1[0-9]|2[1-9]|3[0-1]) down to ([0]?[1-9]|[1-2]\\d|3[0-1]) which means an option 0 followed by 1 to 9 or 1,2 followed by a number, or 3 followed by 0 or 1.
1 Last thing, theres no need for [] around the -, and to pass i (ignore case) RegExp accepts it as a second argument.
Working Example:-
function ValidateDate() {
var dtValue = $('#txtEnteredStartDate').val();
var dtRegex = new RegExp("^([0]?[1-9]|[1-2]\\d|3[0-1])-(JAN|FEB|MAR|APR|MAY|JUN|JULY|AUG|SEP|OCT|NOV|DEC)-[1-2]\\d{3}$", 'i');
return dtRegex.test(dtValue);
}
$('.check').click(function() {
if (ValidateDate() == false) {
$('.result').html("Wrong Date Format");
} else {
$('.result').html("Right Date Format");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtEnteredStartDate" value="19-Nov-2015" />
<input type="button" class="check" value="check" />
<span class="result"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With