Accept date from user within particular range - javascript

I have a form through which I want to accept date only within give date range. But, which ever date I am fetching, it is returning false and showing incorrect range.
Following are the codes related-
register.html-
<div class="form-group row">
<label for="date" class="col-sm-2 col-form-label class='control-label' ">Date of Birth</label>
<div class="col-sm-5">
<input type="date" max="2010-12-31" min="1990-01-01" id="dob" placeholder="Date of birth">
</div>
</div>
controller.js-
var dobInput = document.forms["myform"]["dob"].value;
var maxdate = new Date("2010-12-31");
var mindate= new Date("1990-01-01");
if(maxdate>dobInput && dobInput>mindate)
{
alert("correct range");
}
else{
alert("Input out of range");
return false;
}

The Value you're getting is returned as a string, however you're attempting to evaluate this against Date type variables - this will not work as a string to string evaluation will be done lexicographically.
You should instead convert the value to a date first:
var inputDate = new Date(dobInput);
if(maxdate>inputDate && inputDate >mindate){
...

Your input is a string. so convert to Date first and check with getTime method. Correct code is as below..
var dobInput = document.forms["myform"]["dob"].value;
var maxdate = new Date("2010-12-31");
var mindate= new Date("1990-01-01");
var dateToChk = new Date(dobInput);
if(maxdate.getTime()>dobInput.getTime() && dobInput.getTime()>mindate.getTime())
{
alert("correct range");
}
else{
alert("Input out of range");
return false;
}

Related

Subtract date, month and years dynamically and put data as days using Jquery

I want to subtract a user input years from another input years, but so far I had no luck.
I'll create a snippet where you can play.
What I'm trying to do is to make an input field (A) to enter years only. Then after that select any date and subtract it from the input year (A) (date and month are fixed like 31.03.input_year)...
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = year_enter+'-03-31';
var new_date = $('#new_date').val();
if(year_enter != '') {
//alert(current_year);
}
if(new_date != '') {
//alert(new_date);
var total = new_date - current_year;
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
I always get NaN value, my subtract method is incorrect I guess. I tried using setDate(), getDate() etc, but I don't understand the logic.
Thanks in advance...
You can use new Date() to type cast them into date in order to do arithmetic
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = new Date(year_enter + '-03-31');
var new_date = new Date($('#new_date').val());
if (year_enter != '') {
}
if (new_date != '' && year_enter != '') {
if (current_year < new_date) {
$('#answer').val('A must be greater than B');
return;
}
var total = Math.round(Math.abs((current_year.getTime() - new_date.getTime()) / (24*60*60*1000)));
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001"><span style="opacity: 0.5;"> this currently has fixed -month-day(-03-31) </span>
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
Dates can be tricky to handle, but the moment library makes it a lot easier. In my example I take the input of the two fields, parse them into a moment object and calculate their difference in a duration. You can read more on duration in the Moment.js docs.
The code snippet difference is expressed in days. In case you want to change it to months, or years, update the below line.
log(Math.round(duration.as('days')) + 'days');
You can also include several if statements, to check if the difference is a year, display the result in years. If not, and there's a full month, express the result in months and so on.
Here's a working example in days.
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
NOTE: There are a few discussions out there on how to format a date/duration, e.g. 1 year, 2 months, 5 days. Have a look at a possible solution at these discussions if you want something like this.
How can I format time durations exactly using Moment.js?
How do I use format() on a moment.js duration?

javascript not running onBlur

The function to validate the date field is not executing onBlur below. I'm not sure what I'm missing here. Just trying to test a simply validation.
<div class="cell">
<label>DOB</label><br>
<input id="dob" type="text" placeholder="01/01/1980" onBlur="checkForm(this.value);">
</div>
<script type="text/javascript">
function checkForm(form)
{
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(form.dob.value != '' && !form.dob.value.match(re)) {
alert("Invalid date format: " + form.dob.value);
form.dob.focus();
return false;
}
alert("All input fields have been validated!");
return true;
}
<div class="cell">
<label>DOB</label><br>
<input id="startdate" type="text" placeholder="01/01/1980" onblur="checkForm()">
<script>
function checkForm()
{
// regular expression to match required date format
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
var date = document.getElementById("startdate").value;
alert(date);
if(date != '' && !date.match(re)) {
alert("Invalid date format: " + date);
date.focus();
return false;
}
alert("All input fields have been validated!");
return true;
}
</script>
</div>

jQuery Validate add Method dynamically

I have a form that uses jQuery validate, but the form is generated dynamically and I am trying to add an additional method for validating whether a date is before another, if that date has been used before.
The HTML is the following (with the names generated dynamically):
<div class="form-group">
<label class="control-label col-md-2">Read Date</label>
<div class="input-group col-md-4 date date-picker" data-date-format="dd/mm/yyyy">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" class="form-control insert-val" readonly="" name="datepicker_16" aria-required="true" aria-invalid="false">
</div>
<span class="help-block">Enter the date of the reading</span>
<span class="input-group-btn">
<button class="btn default" type="button" style="margin-top: -18px;"><i class="fa fa-calendar"></i></button>
</span>
</div>
<input type="hidden" name="prevdate_16" class="form-control prev-date" value="29/05/2015">
With the following jQuery to validate the date field:
$('#readingForm .insert-val').each(function(){
var prevDate = $(this).parents('.form-group').find('.prev-date').val();
var useLTD = true;
if(prevDate !== ''){
$.validator.addMethod("less_than_date", function(value, element) {
var curDate = value;
var curarr = curDate.split('/');
var curDay = curarr[0];
var curMonth = curarr[1];
var curYear = curarr[2];
var ncurDate = new Date();
ncurDate.setFullYear(curYear, curMonth-1, curDay);
var prevarr = prevDate.split('/');
var prevDay = prevarr[0];
var prevMonth = prevarr[1];
var prevYear = prevarr[2];
var nprevDate = new Date();
nprevDate.setFullYear(prevYear, prevMonth-1, prevDay);
return ncurDate <= nprevDate;
}, "The reading date must be greater than the previous reading date.");
} else {
useLTD = false;
}
$(this).rules( "add", {
required: true,
minlength: 10,
dateITA: true,
less_than_date: useLTD
});
});
Before the I added the "add method", it correctly validated the date, but now it does not, and doesnt accept even if the date is greater than the previous date.
Really stumped on this one, any help would be greatly appreciated.
Ok, as soon as I posted this, I realised that the return was the wrong way round.
Should have been:
return nprevDate <= ncurDate;

Text box entered date should be in dd/MM/yyyy while creating date object using Jscript

enter code hereSuggest me on this..
While creating Date ref(java script), text box value should be treated as dd/MM/yyyy format..
function myFunction1(a)
{
//Here the input format should be dd/MM/yyyy...
//But Date ref taking it as MM/dd/yyyy
var x=new Date(a);
alert(x);
if(x>new Date())
{
alert("Wrong date");
}
else
{
alert("Success");
}
}
----
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onClick="myFunction1(document.getElementById('textbox1').value)" type="button" value="Execute" />
Try this:
var dateString = document.getElementById('<textboxid>').value;
var day = parseInt(dateString.substring(0,2));
var month = parseInt(dateString.substring(3,5));
var year = parseInt(dateString.substring(6,10));
alert(new Date(year, month - 1, day));
To Validate Date, Use this code:
alert(/^(0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](0[1-9]|1[012]|[1-9])[- /.](\d{4})$/.test(dateString));
It will return true if the date is valid else return false.

comparing dates using script in forms

I am trying to validate date based on date entered in first textbox. If second textbox exceeds one year from the date entered in first textbox, then it should display an alert and blank the second date field textbox. Both the textboxes are readonly and gets the values from calender. I tried the below code but the alert is popping up even if the year is not more than a year. Also ,is it possible to pass 'name3' and 'name4' IDs as parameters. I need to apply this code to 10 rows.
<script>
function fixup()
{
var parts = document.getElementById('name3').value.split("-");
parts[2] = Number(parts[2]) + 1;
var pj = parts.join("-");
var x=document.getElementById('name4').value;
if(x>pj)
{
alert("Expiration date should not be greater than one year from start date");
document.getElementById('name4').value = "";
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return fixup()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
I did Below code after suggestions by dm03514. but validation is not working..
function test()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); //parts[2] is year, parts[0] is month and parts[1] is date.
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setDate(parse_sDate.setFullYear(parse_sDate.getMonth() + 12));
if(parse_sDate>parse_eDate)
{
alert("End date should not be greater than one year from start date");
}
}
I would strongly recommend using a library like moment.js for handling dates. It has extensive date formatting and parsing features as well as comparison helpers:
var d1 = moment(document.getElementById('name3').value, 'YYYY-MM-DD');
var d2 = moment(document.getElementById('name4').value, 'YYYY-MM-DD');
var diff = d2.diff(d1, 'years');
if (diff > 0) {
alert("Expiration date should not be greater than one year from start date");
}
See also:Compare two dates in JS

Categories