i've a form user can enter any date , but i want to set a date range validation . for example: from 1-12-2012 to 1-1-2013 and the system can't accept any date from user that not in the range.. i've tried this javascript code but it doesn't give me any alert even when date not in range ..
this is part of my form :
echo "<tr><th bgcolor='FF6600'> Date <font size='4' color='red'>* </font></th>
<td> <input type='date' name='v2' value='' ></td></tr>";
echo "<tr><th bgcolor='FF6600'> Time <font size='4' color='red'>* </font></th>
<td> <input type='time' name='v3' value='' ></td></tr>";
echo "<tr><th bgcolor='FF6600'> Place <font size='4' color='red'>* </font></th>
<td> <input type='text' name='v4' value='' ></td></tr>";
and this is the javascript code
<script language="javascript">
function validation(form)
{
var v2 = document.getElementById('v2');
var date = v2.value;
if ( (v2 > new date('12/12/2012')) &&
(v2 < new date('1/1/2013')) ){
// date is in your valid range
return true;
} else {
// date is not in your valid range
alert("date is not in valid range")
return false;
}
}
</script>
To compare dates, you should be using the unix timestamp, and right now the first date you're getting from the value is a string, and you can't compare that against date objects?
Make sure you have timestamps in unix time, and then compare those:
function validation(form) {
var v2 = document.getElementById('v2'),
date = new Date(v2.value),
d1 = date.getTime(),
d2 = new Date('12/12/2012').getTime(),
d3 = new Date('1/1/2013').getTime();
if (d1 > d2 || d1 < d3) {
return true;
}else{
alert("date is not in valid range")
}
}
You can make a function like this:
function checkMyDateWithinRange(myDdate){
var startDate = new Date(2012, 11, 1);
var endDate = new Date(2012, 0, 1);
if (startDate < myDate && myDate < endDate) {
return true;
}
return false;
}
and test any date like calling this function:
var inputDate= document.getElementById('tbDate'),
date = new Date(inputDate.value);
if(!checkMyDateWithinRange(date)){
alert('Date is not in range!!!');
}
Here is Working Demo
Related
I'm trying to make an alert to user when choose a date. For example, when user choose 2018-09-13, then the alert will show message "7 days later will be 2018-09-20". But instead, the alert message shows 2018-09-137.
<input type="date" name = "date" id = "date" onchange="javascript:var chooseDate=(this.value)+7; alert('7 days later will be '+chooseDate);" >
How should I add days into the date ?? please help, thank you.
this.value will return the date as string using the format YYYY-MM-DD, so if you "add" 7, it will be YYYY-MM-DD7. What you could do is create a new Date object, and then add the days you want, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getDate()+7);
alert('7 days later will be '+chooseDate);
This will give you the complete date, though, which is something you probably don't want, so you would have to get the values you actually need, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getUTCDate()+7);
var futureDate = chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);
alert('7 days later will be '+chooseDate);
Here you have a working example:
<input type="date" name = "date" id = "date" onchange="var chooseDate=new Date(this.value);chooseDate.setDate(chooseDate.getUTCDate()+7);var futureDate=chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);alert('7 days later will be '+futureDate);" >
How about this in :
addDays = function(input_date, days) {
var date = new Date(input_date);
date.setDate(date.getDate() + days);
return date;
}
You then call do addDays(this.value, 7) in onchange().
And, please reference on getDate() and setDate().
You are working with string instead of a date object:
function lPad(val) {
return ((10 > val ? '0' : '') + val);
}
function add(input, unit, value) {
var cur = input.value;
var byValue = Number(value);
if (!/^\d{4}\-\d{2}\-\d{2}$/.test(cur) || !/day|month|year/.test(unit) || isNaN(byValue)) {
console.warn('invalid parameters!');
return false;
}
var dt = new Date(cur.replace(/\-/g, '/'));
if (!dt || isNaN(dt)) {
console.warn('invalid date!');
return false;
}
if ('day' === unit) {
dt.setDate(dt.getDate() + byValue);
} else if ('month' === unit) {
dt.setMonth(dt.getMonth() + byValue);
} else {
dt.setFullYear(dt.getFullYear() + byValue);
}
input.value = [dt.getFullYear(), lPad(1 + dt.getMonth()), lPad(dt.getDate())].join('-');
console.log(cur, value, unit, '=', input.value);
return true;
}
<input type="date" onchange="add(this,'day','+7');" title="+7 days" />
<input type="date" onchange="add(this,'month','-1');" title="-1 month" />
<input type="date" onchange="add(this,'year','+2');" title="+2 year" />
try this one ...
<input type="date" name = "date" id = "date" onchange="ggrr(this)" >
<script>
function ggrr(input){
var dateString = input.value;
var myDate = new Date(dateString);
var d = new Date(Date.parse(myDate));
var y = d.getFullYear();
var da = d.getDate() + 7;
var m = d.getMonth();
console.log(y+':'+m+':'+da);
}
</script>
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
In below Code i want to validate date between 02/08/2017 and 05/08/2017 and give us a alert which is Date is not in range
<script type="text/javascript">
function validate()
{
today = new Date();
fromdt= new Date("02/08/2017");
todate=new Date("05/08/2017");
if( document.myForm.entrydt.value == "" )
{
alert( "Please Select Entry Date!" );
document.myForm.entrydt.focus() ;
return false;
}
else if(!document.myForm.entrydt.value.match(letters3))
{
alert("Entry Date: Enter Only Date Format i.e DD/MM/YYYY");
document.myForm.entrydt.focus() ;
return false;
}
else if (!document.myForm.entrydt.value.today > startdt && !document.myForm.entrydt.value.today < todate)
{
alert("Entry Date: Enter Date in Proper Range");
document.myForm.entrydt.focus() ;
return false;
}
return( true );
}
</script>
==============================================================================
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" class="form-inline" role="form" name="myForm" id="myForm" onsubmit="return(validate());">
<div id="" class="container" >
<div class="form-group">
<label for="entrydt">Entry Date</label>=
<input class="form-control" style='font-weight:bold;text-transform:uppercase;' id="entrydt" type="text" name="entrydt" style='' placeholder="DD/MM/YYYY" value="" size="10">
</div>
</div>
</form>
new Date().getTime() will give time in milliseconds as long value number to compare values
var today = new Date().getTime(); // 1501653935994
var from = new Date("02/08/2017").getTime(); // gives 1486492200000
var to = new Date("05/08/2017").getTime();
if(today >= from && today <= to) {
// your code goes here
}
new Date().getTime()
gives you the timestamp in ms.
var today = new Date().getTime();
var from = new Date("02/08/2017").getTime();
var to = new Date("05/08/2017").getTime();
var withinRange = today >= from && today <= to;
I'm trying to change the color of the input text whenever the$visa_expired is the same date as today. But right now, I get an error saying Invalid Date
Here is my code:
<script type="text/javascript">
function checkFilled() {
var today = new Date();
var expired = new Date("<?php echo $visa_expiry; ?> ");
var inputVal = document.getElementById("expiry");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "red";
window.alert(today);
}
else{
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
</script>
Here is my HTML:
<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
This is similar to what I have done in the past
var inputElement = document.getElementById("expiry");
var inputDate = inputElement.value;
var expired = new Date();
var today = new Date();
expired.setUTCFullYear(inputDate.split("/")[2], inputDate.split("/")[0] - 1, inputDate.split("/")[1]);
if(today === expired) {
inputElement.style.backgroundColor = "red";
window.alert(today);
} else {
inputElement.style.backgroundColor = "yellow";
}
Also it looks like you need to change
<input type="text" class="form-control" size="5" value="$visa_expiry" id="expiry">
To
<input type="text" class="form-control" size="5" value="<?php echo $visa_expiry; ?>" id="expiry">
Just note that since you are using a input form box, its always possible that someone would enter something like 10-12-2016 instead of the 10/12/2016 format you may be expecting. Which would cause the above code to fail. You might want to consider finding a datepicker, or at the least change the
<input type="text">
to
<input type="date">
Then create some code to format the date to what you want.
References
How to change css property using javascript
Converting string to date in js
If 10/13/2016 is the value of $visa_expiry it should not give error.
check this link and run the fiddle it alert date.
http://phpfiddle.org/main/code/hpia-ub40
<script type="text/javascript">
function checkFilled() {
var today = new Date();
var expired = new Date("<?php echo $visa_expiry; ?> ");
var inputVal = document.getElementById("expiry");
if (today >= expired) {
inputVal.style.backgroundColor = "red";
}
else{
inputVal.style.backgroundColor = "yellow";
}
}
checkFilled();
</script>
You are trying to display an Date Object in alert, which expects a string input. You should use getDate() instead.
try this:
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();
today = day + '/' + month + '/' + year
I want new date range in each box, but it return only last text-box date range. I also made text boxes id's dynamic but still I am facing this issues. I have start date and end date for each text box and I calculated date range in PHP for start date and end date and disabled all those dates which is selected by user in their start date and date all is working fine but it returns last textbox dates disabled in datepicker.
Here is the screenshot-
Sample Image
Javascript function for datepicker to disbaled dates for each box -
$(function () {
var count = $('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
alert(dateRange);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
}
});
HTML for create boxes id's dynamic and fetch values from it.
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssStartDate[]" id="projectAssStartDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssEndDate[]" id="projectAssEndDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input id="calendarDateString<?php echo $id;?>" name="calendarDateString<?php echo $id;?>" title='D-MMM-YYYY' type="text" value="<?php echo $string;?>" />
<input id="projectsId" name="projectsId[]" type="hidden" value="<?php echo $rows['PROJECT_ID'];?>" />
<input id="usersId" name="usersId[]" type="hidden" value="<?php echo $rows['UM_ID'];?>" />
Please check the answer and reply whether this is the way you needed it to go. If not please comment what change you want with respect to this below code result. And I'm sorry that I have manipulated few of your values to ease my result. Will give details explanation if this is what you are expecting.
$(function () {
var count = 2;//$('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
// populate the array
var startDatearray= ["index 0","2016-06-15","2016-06-20"]; // you dont need to create this array .. just fetch these dates from your database as u need
var endDatearray=["index 0","2016-06-21","2016-06-25"];
var i;
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
}
});
I've started to work on Javascript recently. What I am testing is checking the DoB in valid format. Next step will be checking the age.
What my HTML code includes is below
<form name="ProcessInfo" action="#" method="POST" enctype="multipart/form-data" target="_self" onsubmit="return checkForm();">
.
.
.
.
<br>
<label for="txtDOB">Date of Birth:* </label>
<input id="txtDOB" type="text" name="txtDOB" size="12">
format: ##/##/####
<br>
.
.
.
</form>
.
.
and I did the following in my .js file
var errMessage = "";
function checkForm() {
validateName();
validateSurname();
carSelect();
validateDOB();
if (errMessage == "") {
} else {
alert(errMessage);
}
}
...
function validateDOB()
{
var dob = document.forms["ProcessInfo"]["txtDOB"].value;
var pattern = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
if (dob == null || dob == "" || !pattern.test(dob)) {
errMessage += "Invalid date of birth\n";
return false;
}
else {
return true
}
}
I tried to check if its valid with regular expression but I always get an alert even if I type the date correctly. And how can I seperate the DD / MM / YYYY to calculate the age?
If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
http://jsfiddle.net/P9TER/
I suggest using moment.js which provides an easy to use method for doing this.
interactive demo
function validate(date){
var eighteenYearsAgo = moment().subtract(18, "years");
var birthday = moment(date);
if (!birthday.isValid()) {
return "invalid date";
}
else if (eighteenYearsAgo.isAfter(birthday)) {
return "okay, you're good";
}
else {
return "sorry, no";
}
}
To include moment in your page, you can use CDNJS:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
I'd utilize the built in Date object to do the validation for me. Even after you switch from - to / you still need to check whether the month is between 0 and 12, the date is between 0 and 31 and the year between 1900 and 2013 for example.
function validateDOB(){
var dob = document.forms["ProcessInfo"]["txtDOB"].value;
var data = dob.split("/");
// using ISO 8601 Date String
if (isNaN(Date.parse(data[2] + "-" + data[1] + "-" + data[0]))) {
return false;
}
return true;
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Example:_Using_parse for more information.
If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:
var dateformat = /^(0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])[\/\-]\d{4}$/;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function dateCheck() {
debugger;
var inputValues = document.getElementById('dateInput').value + ' ' + document.getElementById('monthInput').value + ' ' + document.getElementById('yearInput').value;
var d = new Date();
var n = d.getHours();
var m = d.getMinutes();
var p = d.getSeconds();
var date = document.getElementById("dateInput").value;
var month = document.getElementById("monthInput").value;
var year = document.getElementById("yearInput").value;
var dateCheck = /^(0?[1-9]|[12][0-9]|3[01])$/;
var monthCheck = /^(0[1-9]|1[0-2])$/;
var yearCheck = /^\d{4}$/;
if (month.match(monthCheck) && date.match(dateCheck) && year.match(yearCheck)) {
var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month == 1 || month > 2) {
if (date > ListofDays[month - 1]) {
alert('Invalid date format!');
return false;
}
}
if (month == 2) {
var leapYear = false;
if ((!(year % 4) && year % 100) || !(year % 400)) {
leapYear = true;
}
if ((leapYear == false) && (date >= 29)) {
alert('Invalid date format!');
return false;
}
if ((leapYear == true) && (date > 29)) {
alert('Invalid date format!');
return false;
}
}
var flag = 1
}
else {
alert("invalid date");
}
if (flag == 1) {
alert("the date is:" + inputValues + " " + "The time is:" + n + ":" + m + ":" + p);
}
clear();
}
function clear() {
document.myForm.dateInput.value = "";
document.myForm.monthInput.value = "";
document.myForm.yearInput.value = "";
}
</script>
</head>
<body>
<div>
<form name="myForm" action="#">
<table>
<tr>
<td>Enter Date</td>
<td><input type='text' name='dateInput' id="dateInput" placeholder="Date" maxlength="2" onclick="dateCheck(document.myForm.dateInput)" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"/></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<td>Enter Month</td>
<td><input type='text' name='monthInput' id="monthInput" placeholder="Month" maxlength="2" onclick="dateCheck(document.myForm.dateInput)" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"/></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<td>Enter Year</td>
<td><input type='text' name='yearInput' id="yearInput" placeholder="Year" minlength="4" maxlength="4" onclick="dateCheck()" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"/></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" onclick="dateCheck()"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<td>
Using pattern and check validate:
var input = '33/15/2000';
var pattern = /^((0[1-9]|[12][0-9]|3[01])(\/)(0[13578]|1[02]))|((0[1-9]|[12][0-9])(\/)(02))|((0[1-9]|[12][0-9]|3[0])(\/)(0[469]|11))(\/)\d{4}$/;
alert(pattern.test(input));
You have used regular expression for this format :
DD - MM- YYYY
If you need this format DD/MM/YYYY use
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
It is two problems - is the slashes the right places and is it a valid date.
I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)
The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:
function isValidDate(str) {
var newdate = new Date();
var yyyy = 2000 + Number(str.substr(4, 2));
var mm = Number(str.substr(2, 2)) - 1;
var dd = Number(str.substr(0, 2));
newdate.setFullYear(yyyy);
newdate.setMonth(mm);
newdate.setDate(dd);
return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();
}
console.log(isValidDate('jk'));//false
console.log(isValidDate('290215'));//false
console.log(isValidDate('290216'));//true
console.log(isValidDate('292216'));//false
To get the values use pattern.exec() instead of pattern.test() (the .test() returns a boolean value).
if(!/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2}$/.test($(this).val())){
alert('Date format incorrect (DD/MM/YY)');
$(this).datepicker('setDate', "");
return false;
}
This code will validate date format DD/MM/YY
with leading zero for day and month
var pattern =/^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;
and with both leading zero/without leading zero for day and month
var pattern =/^(0?[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0?[1-9]|1[0-2])\/([0-9]{4})$/;
I use the code I found #.w3resources
The code takes care of
month being less than 12,
days being less than 32
even works with leap years.
While Using in my project for leap year I modify the code like
if ((lyear==false) && (dd>=29))
{
alert('Invalid date format!');
return false;
}
if ((lyear==false) && (dd>=29))
{
alert('not a Leap year February cannot have more than 28days');
return false;
}
Rather than throwing the generic "Invalid date format" error which does not make much sense to the user.
I modify the rest of the code to provide valid error message like month cannot be more than 12, days cannot be more than 31 etc.,
The problem with using Regular expression is it is difficult to identify exactly what went wrong. It either gives a True or a false-Without any reason why it failed. We have to write multiple regular expressions to sort this problem.
var date=/^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{1,4}$/;
if(!date.test(form.date.value))
alert("Enter correct date");
else
alert(" working");
You can use attributes of html tag instead of validation from html input type ="date" can be used instead of validating it. That's the benifits html 5 gives you
If you're using moment then that's the single line code:
moment(date).format("DD/MM/YYYY").isValid()
When we put only pattern it's not simple to check every possible date combination. Users can enter valid numbers like 99/99/9999 but it's not a valid date. Even If we limit days and months to a more restrictive value (30/31 days and 0-12 months) we still may get a case where we have leap year, febraury etc. and we cannot properly validate them using regex. So the better approach is to use a date object itself.
let InputDate = "99/99/9999"
let pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
let editDate = InputDate.replace("\/","-")
let dateValidation = function validation(){
if(pattern.test(InputDate) && new Date(editDate) == 'Invalid Date'){
return false;
}else{
return true;
}
}
console.log(dateValidation()) //Return false