Why this function load the server? - javascript

I have this function.
It's a validation for register page, need to check if the date is vaild.
I have another function which work well and doesnt run if validation fails.
I thought maybe its in the Validator itself , but as i said, i have another function (and another validator which calls the other function) that work well and I didnt manage to find any diffrences.
CODES:
Failing Function:
function CheckDate(sender, args)
{
var DateReg = document.getElementById("DateReg").value;
DateReg = DateReg.split('/');
var day = DateReg[0];
var month = DateReg[1];
var year = DateReg[2];
var CurrentYear = new Date().getFullYear();
args.IsValid = true;
if (day < 1 || day > 31 || month < 1 || month > 12 || year > CurrentYear || year < CurrentYear - 120)
{
args.IsValid = false; // לא תקין
}
return args.IsValid;
}
Failing Validator:
<asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="CheckDate" runat="server" ErrorMessage="type age again"> </asp:CustomValidator>
Working Validator:
<asp:CustomValidator ID="CustomValidator2" ClientValidationFunction="CheckInterest" runat="server" ErrorMessage="choose interest"> </asp:CustomValidator>
Any suggestions?
Thanks

Modified version that will validate on a date in the following format "mm/dd/yyyy".
var btnRun = document.getElementById("btnRun");
btnRun.addEventListener('click',function(e){
CheckDate();
});
function CheckDate(sender, args)
{
var isValid = false;
var DateReg = document.getElementById("DateReg").value;
var date = new Date(DateReg);
var cDate = new Date();
var CurrentYear = cDate.getFullYear();
isValid = true;
var iday = date.getDay() + 1;
var iMonth = date.getMonth() + 1;
var iYear = date.getFullYear();
if (iday < 1 || iday > 31 || iMonth < 1 || iMonth > 12 || iYear > CurrentYear || iYear < CurrentYear - 120)
{
isValid = false;
}
console.log(isValid);//just used to show that it works
return isValid;
}
<input id="DateReg" />
<button id="btnRun">Run</button>

Ok; Got it
the getElementById did it
Changed it to
var DateReg = document.getElementById('<%=DateReg.ClientID %>').value;
Seems to work now

Related

Subtracting dates in javascript

I am working on a Onchange() event form.
Form example
By default, the Present Value as of date is today. If a user enters Remaining payments = 12 months then the
End of Lease = Present Value as of date + Remaining payment (i.e months).
For my onchange event i am trying to calculate Start of Lease automatically.
Here, Start of Lease = End of lease - Remaining payment.
Here is my code so far. The issue i am having is that the Start of Lease date is getting reflected but it's returning a day less than End of Lease. However, the first part calculating the End of Lease itself is working fine.
function PopulateEndDate() {
debugger;
var d2;
var paymentDays;
var stDate;
var pDate;
var etDate;
var ddlFrequency = document.getElementById("ddFrequency");
var selectedFrequency = ddlFrequency.options[ddlFrequency.selectedIndex].value;
if (document.getElementById("startDate"))
stDate = document.getElementById("startDate").value;
if (document.getElementById("presentDate"))
pDate = document.getElementById("presentDate").value;
var today = new Date();
if (stDate)
d2 = new Date(stDate);
else
d2 = new Date(pDate);
if (document.getElementById("paymentRemaining")) {
if (selectedFrequency == "D") {
paymentDays = document.getElementById("paymentRemaining").value;
}
else if (selectedFrequency == "Q") {
paymentDays = document.getElementById("paymentRemaining").value * 3;
}
}
if (paymentDays && paymentDays != "")
d2.setMonth(d2.getMonth() + parseInt(paymentDays));
if (document.getElementById("endDate"))
document.getElementById("endDate").value = getCurrentDay(d2);
var endDate = document.getElementById("endDate").value;
if (endDate)
etDate = new Date(endDate);
if (stDate == null && paymentDays && paymentDays != "")
{
etDate.setMonth(etDate.getMonth() - parseInt(paymentDays));
}
if (document.getElementById("startDate"))
document.getElementById("startDate").value = getCurrentDay(etDate);
}
I am not sure what i am doing wrong here. Any help will be greatly appreciated. Thank you.
if (endDate){
var etDate = new Date(endDate);
var eDay = etDate.getUTCDate()+1;
var eMonth = etDate.getUTCMonth()+1;
var eYear = etDate.getUTCFullYear()-1;
var sDate = eYear + "-" + eMonth + "-" + eDay;
if (stDate == null)
{
sDate.setMonth(sDate.getDay() - parseInt(paymentDays));
}
if (document.getElementById("startDate"))
document.getElementById("startDate").value = getCurrentDay(sDate);
This helped solve my problem.

Difference between dates JS

This is the script i use for the date:
<script type="text/javascript">
var datefield=document.createElement("input")
datefield.setAttribute("type", "date")
if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
}
</script>
Alert is not working when the requirement is not fullfilled. Below is my code:
function validateForm() {
var x = document.forms["myForm"]["from"].value;
if (x == null || x == "") {
alert("please choose the date");
return false;
}
var y = document.forms["myForm"]["to"].value;
if (y == null || y == "") {
alert("please choose the date");
return false;
}
var date1 = new Date("x");
var date2 = new Date("y");
var diffDays = (date1 - date2);
var totalSeconds = diffDays / 1000;
var days = Math.floor(totalSeconds / 86400);
if(days < 7 )
{
alert("please be more than 7 days");
return false;
}
I have problem in getting the range between the dates. Any help will be appreciated.
You are passing the variables x and y into the Date object as strings. Remove the " around them.
var date1 = new Date(x);
var date2 = new Date(y);
change:
var date1 = new Date("x");
var date2 = new Date("y");
to:
var date1 = new Date(x);
var date2 = new Date(y);
Also see How can I tell if a browser supports <input type='date'> for more reliably check if the date type is supported.

Compare times from converted time format

I have 2 different times. Now I want to compare these 2 times which are of the same date. I want to check which is the greater time. How can I do that. This is my code:
start_time = 10:30 AM
end_time = 12:30 PM
function modify_time(){
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
if (start_time != '' && end_time != '') {
alert(start_time); alert(end_time);
if (end_time <= start_time) {
alert('select valid time');
$('#start_time').val('');
$('#end_time').val('');
}
}
}
Thank You.
I hope you are looking for such logic:
var start_time = "10:30 AM";
var end_time = "10:20 AM";
start_time = start_time.toLowerCase();
end_time = end_time.toLowerCase();
function getMin(timeStrin)
{
var isPM = false;
if(timeStrin.indexOf("pm") > -1)
isPM = true;
timeStrin = timeStrin.replace("am","");
timeStrin = timeStrin.replace("pm","");
var timeArr = timeStrin.split(":");
var hr = parseInt(timeArr[0],10);
var min = parseInt(timeArr[1],10);
if(isPM && hr>=1 && hr != 12)
hr = hr+12;
return (hr*60 + min);
}
if (start_time != '' && end_time != '') {
start_time = getMin(start_time);
end_time = getMin(end_time);
alert(start_time);
alert(end_time);
if (end_time <= start_time) {
alert('select valid time');
}
}
Add the same static date in front of both time and use below coding
var d=new Date("October 16, 1990 10:30 AM");
var starttime = d.getTime();
var d=new Date("October 16, 1990 12:30 PM");
var endtime = d.getTime();
if(start_time!='' && end_time!=''){ alert(start_time); alert(end_time);
if(end_time<=start_time){
alert('select valid time');
$('#start_time').val('');
$('#end_time').val('');
}
}
Try This Example..
//Set the extracted part of the time to variables.
// If you dont have the second part then set it to 0.
var startHour = extractedStartHour;
var startMinute = extractedStartMinute;
var startSecond = extractedStartSecond;
var endHour = extractedEndHour;
var endMinute = extractedEndMinute;
var endSecond = extractedEndSecond;
//Create date object and set the time to that
var startTimeObject = new Date();
startTimeObject.setHours(startHour, startMinute, startSecond);
//Create date object and set the time to that
var endTimeObject = new Date(startTimeObject);
endTimeObject.setHours(endHour, endMinute, endSecond);
//Now we are ready to compare both the dates
if (startTimeObject > endTimeObject) {
alert('End time should be after start time.');
} else {
alert('Entries are perfect.');
}
For simplicity, just convert to a number and add an offset for PM.
replace(/\D/g,'') will replace all non numeric chars with nothing.
var startTime = $('#start_time').val();
var endTime = $('#end_time').val();
var startTimeValue = parseInt(startTime.replace(/\D/g,''));
var endTimeValue = parseInt(endTime.replace(/\D/g,''));
startTimeValue += startTime.indexOf("PM") > -1 ? 1200 : 0;
endTimeValue += endTime.indexOf("PM") > -1 ? 1200 : 0;
alert(startTimeValue <= endTimeValue);
Try it
function modify_time(){
var start_time=$('#start_time').val();
var end_time=$('#end_time').val();
if(start_time!='' && end_time!=''){alert(start_time); alert(end_time);
var s_time = start_time.split(":");
var e_time = start_time.split(":");
if( s_time[0] > e_time[0]){
alert('select valid time');
$('#start_time').val('');
$('#end_time').val('');
}else if(s_time[0] == e_time[0]){
if(s_time[1] >=e_time[1]){
alert('select valid time');
$('#start_time').val('');
$('#end_time').val('');
}
}
}
}

Failed to load resource javascript window.location

Trying to validate an age from one form i found this issue on the console of chrome.
this is my code:
<script type="text/javascript">
function CalAge() {
var dd = $("#day").val();
var mm = $("#month").val();
var yy = $("#year").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(yy, mm-1, dd);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if(dd !=0 || mm !=0 || yy !=0){ //whether one or all values havent been choosen
if ((currdate - mydate) < 18){
window.location = "http://www.google.com";
}
else{
alert("more than 18");
}
}
else{
alert("please register");
}
}
</script>
i wonder if is something to do with my code, because if i put the url relocation in somewhere else in the code (like on top of the conditions) it works just fine.
any suggestion
It's because if ((currdate - mydate) < 18) isn't evaluating to true.
In your example, currdate is the cutoff date for being 18 years old. Your condition should be:
if (currdate < mydate) { ... }
That is, if someone is born after the cutoff date (i.e., is less than 18 years old), then redirect to Google.
That's a good explanation given to the error... I think you have to replace the window.location with something like this: window.location.assign("http://www.google.com") and also use only one else to alert all your popups! If optional... Good luck!
Oookay! Use this:
`
function CalAge() {
var dd = $("#day").val();
var mm = $("#month").val();
var yy = $("#year").val();
var age = 18;
var mydate = new Date();
mydate.setFullYear(yy, mm-1, dd);
var currdate = new Date();
currdate.setFullYear(currdate.getFullYear() - age);
if(dd !=0 || mm !=0 || yy !=0){ //whether one or all values havent been choosen
var subit = currdate - mydate;
if (subit < 18){
window.location.href = "http://www.google.com";
}
else{
alert("more than 18");
}
}
else{
alert("please register");
}
}
</script>`
thanks good luck

Check if one date is between two dates

I need to check if a date - a string in dd/mm/yyyy format -
falls between two other dates having the same format dd/mm/yyyy
I tried this, but it doesn't work:
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
alert("date contained");
I used debugger and checked, the to and from variables have isNaN value.
Could you help me?
Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
console.log(check > from && check < to)
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Here is a Date Prototype method written in typescript:
Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
return !minDate ? true : this.getTime() >= minDate.getTime()
&& !maxDate ? true : this.getTime() <= maxDate.getTime();
};
I did the same thing that #Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];
dates.forEach(element => {
let parts = element.split("/");
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
if (date >= from && date < to) {
console.log('dates in range', date);
}
})
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle:
https://jsfiddle.net/zm75cq2a/
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This may feel a bit more intuitive. The parameter is just a valid date string.
This function returns true if the date passed as argument is in the current week, or false if not.
function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()
// create a date instance with the function parameter
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)
// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date by substracting the day index (number) in the week from the day value (count)
//in the month (like october 15th - 5 (-> saturday index)) and +1 because
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Fiddle
This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.
const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';
if (
DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
console.log('within range');
} else {
console.log('not in range');
}

Categories

Resources