pls can somebody give the date validation regex, which will allow the following rules are
It should allow mm/dd/yyyy, m/d/yyyy, mm/d/yyyy, m/d/yyyy (not allow yy)
Number of days for month (30 and 31) validation.
Feb month validation for leap & non leap years.
Don't try to parse date entirely with regex!Follow KISS principle..
1>Get the dates with this regex
^(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})$
2> Validate month,year,day if the string matches with above regex!
var match = myRegexp.exec(myString);
parseInt(match[0],10);//month
parseInt(match[1],10);//day
parseInt(match[2],10);//year
Try this:
([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})
and then if you got a valid string from the above regex then with string manipulations, do something like below:
if(/([0-9][1-2])\/([0-2][0-9]|[3][0-1])\/((19|20)[0-9]{2})/.test(text)){
var tokens = text.split('/'); // text.split('\/');
var day = parseInt(tokens[0], 10);
var month = parseInt(tokens[1], 10);
var year = parseInt(tokens[2], 10);
}
else{
//show error
//Invalid date format
}
Here's a full validation routine
var myInput = s="5/9/2013";
var r = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
if(!r.test(myInput)) {
alert("Invalid Input");
return;
}
var a = s.match(r), d = new Date(a[3],a[1] - 1,a[2]);
if(d.getFullYear() != a[3] || d.getMonth() + 1 != a[1] || d.getDate() != a[2]) {
alert("Invalid Date");
return;
}
// process valid date
Related
I was referring this link and as I do not have 50 reputation I am not allowed to comment in the answer so posting this question. I did not get the statement where you can see a month is subtracted from months. This can be simple one but could anyone please clarify on this?
var m = matches1 - 1; ?
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
var m = matches1 - 1; ?
months index starts from 0.
So while you think Jan is 1, it is actually 0 when you do date.getMonth().
Which is why when you get 1 from a date-string, you need to make it 0 before setting it to a date object.
In the spirt of the question, the validation function is way overdone. Only the month needs to be checked since if either the day or month is out of bounds, the month of the generated date will change.
Also the regular expression can be greatly simplified, consider (assuming the input is the peculiar US m/d/y format):
/* Validate a date string in US m/d/y format
** #param {string} s - string to parse
** separator can be any non–digit character (.-/ are common)
** leading zeros on values are optional
** #returns {boolean} true if string is a valid date, false otherwise
*/
function validateMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2],--b[0],b[1]);
return b[0] == d.getMonth();
}
var testData = ['2/29/2016', // Valid - leap year
'2/29/2015', // Invalid - day out of range
'13/4/2016', // Invalid - month out of range
'13/40/2016', // Invalid - month and day out of range
'02/02/2017']; // Valid
document.write(testData.map(function(a) {
return a + ': ' + validateMDY(a);
}).join('<br>'));
Java script function
<script language="JavaScript">
function checkdate(date1){
var validformat=/^\d{2}\/\d{2}\/\d{4} \d{2}\:\d{2}\:\d{2}$/
if(!validformat.test(date1.value)){
alert("Invalid Date");
document.form.date1.value="";
}
}
The above is working well ! but I want to restrict the month and days accordingly.
my format = mm/dd/YYYY hh:mm:ss
Month should not be more than 12 and less than 1 and same , date should not be more than 31 and less than 1;
one thing more !
02/02/2013 00:00:00 is valid date but 2/2/2013 00:00:00 showing as a invalid date.
How to control these two situations ?
DateTime RegEx for the m/d/YYYY hh:mm:ss and mm/dd/YYYY hh:mm:ss
/^(0?[1-9]|1[012])\/(0?[1-9]|[12]\d|3[01])\/[12]\d{3} ([01]\d|2[0-3])\:[0-5]\d\:[0-5]\d$/
Explained demo: http://regex101.com/r/bS0gB6
You can try the following method:
var comp = value.split('/');
var d = parseInt(comp[0], 10);
var m = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y, m - 1, d);
var validDateFormat = false;
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
validDateFormat = true;
}
if validDateFormat is true, the date is valid.
You can take a look at this website which allows you to create regular expressions for numeric ranges.
That being said, you should use numerical operators provided by the language your are using (Javascript) for numeric operations and not regular expressions.
Alternatively, you could use a DateTime Picker created in JQuery, as shown here.
I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012"; // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}
I am using MaskedEditExtender for entering a datetime. I am unable to figure out how to validate it.
Is there any Regular Expression for validating dates along with time MM/dd/yyyy hh:mm
or any Javascript function ??
THis will solve your issue:
^(([0]?[1-9]|1[0-2])/([0-2]?[0-9]|3[0-1])/[1-2]\d{3}) (20|21|22|23|[0-1]?\d{1}):([0-5]?\d{1})$
Javascript has Date.parse
it takes US formatted date of mm/dd/yyyy hh:mm:ss and with that format it works in all browsers I have tested: Firefox, Safari, Chrome, Edge
console.log(new Date(Date.parse("03/25/2022 12:00")))
will return 10th September 2011 at noon
Use DateTime.Parse or DateTime.TryParse (there are also ParseExact and TryParseExact equivalents).
If the string does not represent a valid DateTime it will not parse.
DateTime myDateTime = DateTime.ParseExact(myString,
"MM/dd/yyyy hh:mm",
CultureInfo.InvariantCulture);
The above will throw an exception if the value is not parseable. Use the Try variant if you want to avoid the chance of the exception being thrown - this requires an out parameter and testing the return value of the function for success.
And just in case you want the regular expression, this should work:
^(0[1-9]|1[012])/(0[1-9]|[12][0-9]|3[01])/(19|20)\d\d ([01]\d|2[0-3]):[0-5]\d$
The following Regex:
^([1-9]|([012][0-9])|(3[01]))\/([0]{0,1}[1-9]|1[012])\/([1-2][0-9][0-9][0-9]) [0-2][0-9]:[0-9][0-9]
gives this result:
03/03/2021 02:12
You may try following Function that Validates date in "dd/MM/yyyy HH:mm" format
function ValidateDate(dt) {
try {
var isValidDate = false;
var arr1 = dt.split('/');
var year=0;var month=0;var day=0;var hour=0;var minute=0;var sec=0;
if(arr1.length == 3)
{
var arr2 = arr1[2].split(' ');
if(arr2.length == 2)
{
var arr3 = arr2[1].split(':');
try{
year = parseInt(arr2[0],10);
month = parseInt(arr1[1],10);
day = parseInt(arr1[0],10);
hour = parseInt(arr3[0],10);
minute = parseInt(arr3[1],10);
//sec = parseInt(arr3[0],10);
sec = 0;
var isValidTime=false;
if(hour >=0 && hour <=23 && minute >=0 && minute<=59 && sec >=0 && sec<=59)
isValidTime=true;
else if(hour ==24 && minute ==0 && sec==0)
isValidTime=true;
if(isValidTime)
{
var isLeapYear = false;
if(year % 4 == 0)
isLeapYear = true;
if((month==4 || month==6|| month==9|| month==11) && (day>=0 && day <= 30))
isValidDate=true;
else if((month!=2) && (day>=0 && day <= 31))
isValidDate=true;
if(!isValidDate){
if(isLeapYear)
{
if(month==2 && (day>=0 && day <= 29))
isValidDate=true;
}
else
{
if(month==2 && (day>=0 && day <= 28))
isValidDate=true;
}
}
}
}
catch(er){isValidDate = false;}
}
}
return isValidDate;
}
catch (err) { alert('ValidateDate: ' + err); }
}
I have a requirement by which need to check validation between number of days entered between two date selectors [From & To Dates]. My requirement is that it should not exceed 100 days.
Is there a way I can do with asp.net provided validators. I can go ahead and write customvalidator for it (both client and server side), but wondering if that is doable using CompareValidator or RangeValidator?
Try using custom validator:
<asp:CustomValidator ID="valCustmCheckDate" runat="server" ErrorMessage="The date difference should not be greater than 100 days" ForeColor="Red" ValidationGroup="LoginUserAdd" ClientValidationFunction="CompareStartAndEndDate"></asp:CustomValidator>
Call the following function in javascript:
function CompareStartAndEndDate(sender,args) {
var txtFromExpiryDate = document.getElementById('<%=txtFromDate.ClientID %>');//dd/mm/yyyy format
var txtToExpiryDate = document.getElementById('<%=txtToDate.ClientID %>');//dd/mm/yyyy format
var a = txtFromDate.value.split('/');
var b = txtToDate.value.split('/');
var FromDate = new Date(a[2], a[1] - 1, a[0]);
var ToDate = new Date(b[2], b[1] - 1, b[0]);
var newFromDate =FromDate.getTime();
var newToDate=ToDate.getTime();
var dateDiffInMilliseconds= newToDate-newFromDate;
var dateDiffInDays=dateDiffInMilliseconds/(1000 * 60 * 60 * 24)
if (dateDiffInDays>100 ) {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
Hope this will do it for you...
Below function will do the work if you are looking after similar kinda answer
function CheckDateRange(start, end, numberOfDays) {
// Parse the entries
var startDate = Date.parse(start);
var endDate = Date.parse(end);
// Make sure they are valid
if (isNaN(startDate)) {
alert("The start date provided is not valid, please enter a valid date.");
return false;
}
if (isNaN(endDate)) {
alert("The end date provided is not valid, please enter a valid date.");
return false;
}
// Check the date range, 86400000 is the number of milliseconds in one day
var difference = (endDate - startDate) / (86400000 * numberOfDays);
if (difference < 0) {
alert("The start date must come before the end date.");
return false;
}
if (difference >= 1) {
alert("The range must not exceed 100 days.");
return false;
}
return true;
}
Got help from somewhat similar post