ASP.Net validation for number of days between Arrival & Departure days - javascript

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

Related

Date validation for months in javascript

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>'));

Get Month as well as date in my variable - javascript

Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers

check whether the date entered by the user is current date or the future date

I was browsing through the net to find a javascript function
which can check whether the date entered by the user is current date or the future date but i didn't found a suitable answer so i made it myself.Wondering If this can be achieved by one line code.
function isfutureDate(value)
{
var now = new Date;
var target = new Date(value);
if (target.getFullYear() > now.getFullYear())
{
return true;
}
else if(target.getFullYear() == now.getFullYear())
{
if (target.getMonth() > now.getMonth()) {
return true;
}
else if(target.getMonth() == now.getMonth())
{
if (target.getDate() >= now.getDate()) {
return true;
}
else
{
return false
}
}
}
else{
return false;
}
}
You can compare two dates as if they were Integers:
var now = new Date();
if (before < now) {
// selected date is in the past
}
Just both of them must be Date.
First search in google leads to this: Check if date is in the past Javascript
However, if you love programming, here's a tip:
A date formatted like YYYY-MM-DD could be something like 28-12-2013.
And if we reverse the date, it is 2013-12-28.
We remove the colons, and we get 20131228.
We set an other date: 2013-11-27 which finally is 20131127.
We can perform a simple operation: 20131228 - 20131127
Enjoy.
here's a version that only compares the date and excludes the time.
Typescript
const inFuture = (date: Date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
ES6
const inFuture = (date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
try out this
function isFutureDate(idate){
var today = new Date().getTime(),
idate = idate.split("/");
idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
return (today - idate) < 0 ? true : false;
}
Demo
console.log(isFutureDate("02/03/2016")); // true
console.log(isFutureDate("01/01/2016")); // false
ES6 version with tolerable future option.
I made this little function that allows for some wiggle room (incase data coming in is from a slightly fast clock for example).
It takes a Date object and toleranceMillis which is the number of seconds into the future that is acceptable (defaults to 0).
const isDistantFuture = (date, toleranceMillis = 0) => {
// number of milliseconds tolerance (i.e. 60000 == one minute)
return date.getTime() > Date.now() + toleranceMillis
}
try this
function IsFutureDate(dateVal) {
var Currentdate = new Date();
dateVal= dateVal.split("/");
var year = Currentdate.getFullYear();
if (year < dateVal[2]) {
return false;//future date
}
else {
return true; //past date
}
}
In my case, I used DD-MM-YYYY format dates to compare and it gives an error since the behaviour of "DD-MM-YYYY" is undefined. So I convert it to a compatible format and compare it. And also if you need to compare only the dates and not time, you need to set time parameters to zero.
var inputDateVal = "14-06-2021";
if (inputDateVal != null && inputDateVal != '') {
var dateArr = inputDateVal.split("-");
var inputDate = new Date('"' + dateArr[2] + "-" + dateArr[1] + "-" + dateArr[0] + '"').setHours(0, 0, 0, 0);
var toDay = new Date().setHours(0, 0, 0, 0);
if(inputDate > toDay){
console.log("Date is a future date");
}else if(inputDate== toDay){
console.log("Date is equal to today");
}else{
console.log("Date is a past date");
}
}
You can use moment.js library
let dateToBeCompared = "10/24/2021"; // "DD/MM/YYYY" format
// For past dates
moment(dateToBeCompared, "DD/MM/YYYY").isBefore(moment(new Date(), "DD/MM/YYYY"),
'day')
// For same dates
moment(dateToBeCompared, "DD/MM/YYYY").isSame(moment(new Date(), "DD/MM/YYYY"),
'day')
// For future dates
moment(dateToBeCompared, "DD/MM/YYYY").isAfter(moment(new Date(), "DD/MM/YYYY"),
'day');
There are other functions like also like isSameOrAfter() and isSameOrBefore()
Have a look at here

Regex for Date Validation in javascript

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

Comparing two dates with javascript or datejs (date difference)

I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.
I am having a hard time finding out how to do this, my current code won't work.
<script src="inc/date-fi-FI.js" type="text/javascript"></script>
<script type="text/javascript">
function parseDate() {
var date = $('#date').val();
var parsedDate = Date.parse(date);
alert('Parsed date: '+parsedDate);
}
function jämförMedIdag (datum) {
if (datum == null || datum == "") {
alert('Inget datum!');
return;
}
/*resultat = Date.compare(Datum1,Datum2);
alert(resultat); */
var datum = Date.parse(datum);
var dagar = datum.getDate();
var månader = datum.getMonth();
var år = datum.getYear();
var nyttDatum = new Date();
nyttDatum.setFullYear(år,månader,dagar);
var idag = new Date();
if(nyttDatum>idag) {
var svar = nyttDatum - idag;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
} else {
var svar = idag - nyttDatum;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
}
}
</script>
This code will try to calculate the difference between two dates, one of them being today. No success lolz.
Thanks in advance!
My final code (thanks RobG!):
function dateDiff(a,b,format) {
var milliseconds = toDate(a) - toDate(b);
var days = milliseconds / 86400000;
var hours = milliseconds / 3600000;
var weeks = milliseconds / 604800000;
var months = milliseconds / 2628000000;
var years = milliseconds / 31557600000;
if (format == "h") {
return Math.round(hours);
}
if (format == "d") {
return Math.round(days);
}
if (format == "w") {
return Math.round(weeks);
}
if (format == "m") {
return Math.round(months);
}
if (format == "y") {
return Math.round(years);
}
}
It is not fully accurate, but very close. I ended up adding some addons to it to calculate in day week month year or hour, anyone can freely copy and use this code.
If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:
Example
// dd.mm.YYYY or d.m.YYYY
// dd.m.YYYY or d.mm.YYYY
var start = Date.parse("20.09.2011");
var end = Date.parse("28.09.2011");
var span = new TimeSpan(end - start);
span.days; // 8
Of course the above could be simplified down to one line if you really want to be extra terse.
Example
new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings
Hope this helps.
If your dates are strings in the common form d/m/y or some variation thereof, you can use:
function toDate(s) {
var s = s.split('/');
return new Date(s[2], --s[1], s[0]);
}
You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.
Edit to answer comments
To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:
var s = s.split(/[/\.-]/);
The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].
/Edit
To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).
So if you want to see how many days are between today and a date, use:
function diffToToday(s) {
var today = new Date();
today.setHours(0,0,0);
return Math.round((toDate(s) - today) / 8.64e7);
}
alert(diffToToday('2/8/2011')); // -1
alert(diffToToday('2/8/2012')); // 365
PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.
Using the Date object:
var today = Date.today();
var dateToday = Date.parse(today.toString('MMMM d, yyyy'));
var prevMonthDate = dateToday.addDays(-30);
var difference = (dateToday - prevMonthDate)/86400000;
console.log(difference); //will give you the difference in days.

Categories