Checking difference between two date and display custom message - javascript

Hello I have input on registration form and want to retrieve the value of input and compare it with the current date using JavaScript and display message after check age if age less than 18 year and display custom message on the bottom of input.
var dateControl = document.querySelector('input[type="date"]').getFullYear();
var startDate = new Date(document.getElementById('date1').value);
and this is the HTML
<input type="date" name="date" class="form-control" id="date1" value="{{ old('date', date('Y-m-d')) }} " onclick="checkDate()">
<div id="currentdate"></div>
but is give old value after each click.
and the message not displayed
Best regards

Not much code to go from but I think you may need this function anyway to compare the date you receive from the form with the current date and get the difference
function process() {
var today = new Date();
var date = new Date(document.getElementById("date1").value);
var diff = Number((today.getTime() - date.getTime()) / 31536000000).toFixed(0);
if (diff >= 18) {
// Your form submission goes here
console.log("success");
} else {
// your error handeling goes here
console.log("error");
}
}
PS: That this method won't give you the difference in an exact way,
it will just give you the difference between the years.

Related

Broken Delivery Estimate Calculator

I'm hoping someone can help me figure out how to code an app that allows you to select a mailing date with jquery datepicker, select Standard or First-class shipping from a dropdown, and calculate an estimated delivery date window (7-12 Days for Standard, 3-5 Days for First-class).
I had it working when the "Mailing in" [number] "Days" accepted a string input but then it broke when I added code for the datepicker.
I also need to keep weekends & holidays excluded from the shipping calculation.
Here's a link to the full pen: https://codepen.io/allyjfuller/pen/oNXvwJL
$('#calculateShippingEstimate').click(function( event ) {
//Prevent button from 'submitting' and reloading the page
event.preventDefault();
//Capture the mailing date
var $mailingDate = $("#mailingDate").val();
var $postageType = $("#postageType").val();
var $shipStateShippingDuration = eval('data.shipTimes.' + $postageType);
var $totalShippingTime = parseInt($mailingDate) + parseInt($shipStateShippingDuration);
//Create the date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate() + parseInt($totalShippingTime);
var year = date.getFullYear();
<form>
<section>
<label>Mailing on</label>
<input id="mailingDate" placeholder="number"></input>
</section>
<section>
<label>Postage:</label>
<select id="postageType">
<option value="Standard">Standard</option>
<option value="FirstClass">First-Class</option>
</select>
</section>
<input class="button" id="calculateShippingEstimate" type="submit" value="Get Estimated Delivery Date"></input>
<div class="results"></div>
</form>
Looking through your code snippet it seems like you're trying to hand roll a lot of features that already exist within the JS Date framework.
Once you get the starting date and the number of days for shipping, you can add those days together to create a final shipping date. From there and within a loop, you may go day by day and check whether the current date index is a weekday or not (using Date.getDay()).
With that you may check for Saturday [6] and Sunday [0] and then add days needed on top of the final date.
I've included my version of the code below with some console debugging but have not added code holidays. Holidays may be checked for using an array or map. Get all the holiday dates for a year and then have the current index check the holiday array/map to see if there are any matches. If there are, add another day to the final date.
The function for addDays is pulled from here. It adds some explanation which I think you'll find helpful.
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
// FINAL SHIPPING ESTIMATE
$('#calculateShippingEstimate').click(function( event ) {
event.preventDefault();
let mailingDateVal = $("#mailingDate").val();
let shippingDuration = data.shipTimes[$("#postageType").val()];
let mailingDate = new Date(mailingDateVal);
console.log("final Date: " + addDays(mailingDate, shippingDuration));
let finalDate = addDays(mailingDate, shippingDuration)
let mailingDateIndex = new Date(mailingDate);
while(mailingDateIndex <= finalDate) {
console.log("current mailDateIndex: " + mailingDateIndex)
if (mailingDateIndex === finalDate) {
break;
}
// Weekend
console.log(mailingDateIndex.getDay());
if (mailingDateIndex.getDay() == 0 || mailingDateIndex.getDay() == 6) {
console.log("weekend day hit! Adding day to final...")
finalDate = addDays(finalDate, 1);
}
mailingDateIndex = addDays(mailingDateIndex, 1);
}
});

Cant quite invalidate/validate dates correctly (arrival date) ?

This is my html code with a snippet of just the code I am trying to use to invalidate/validate date entries with hopefully all of the corresponding and necessary variables declared.
<html>
<head>
<title> Booking Page </title>
<script>
function Booking(){
var departuredate = document.getElementById("departdate").value; //departure date selected by user
var arrivaldate = document.getElementById("arrivedate").value; //arrival date selected by user
departuredate = new Date(departuredate);
arrivaldate = new Date(arrivaldate);
CurrentDate = new Date(); //todays date
month = '' + (arrivaldate.getMonth() + 1),
day = '' + arrivaldate.getDate(),
year = arrivaldate.getFullYear();
var adate = [day, month, year].join('/');
alert(adate);
the adate is for the arrival date only. I plan to just copy and adjust the code across once it is correct for the departure date. Currently the code seems to invalidate all entries, not allowing completely valid entries to be validated.
var re = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
if (!adate.match(re))
{
document.getElementById("temp").innerHTML = "Incorrect format"
document.MyForm.arrivedate.focus();
document.getElementById("arrivedate").style.border='1px solid red';
return false;
}
else
{
// if none of the above situaton's occur then the input is true and validated
alert('Dates are validated');
return true;
}
}
</script>
</head>
<body>
<H1> Booking Form </H1>
<Form action="testpage.py" method="POST" name="MyForm" onsubmit="return Booking()">
<p>Departure Date:</p>
<input type=date name="departdate" id="departdate" >
<p>Arrival Date:</p>
<input type=date name="arrivedate" id="arrivedate">
<input type=submit value="Find flights">
</Form>
</body>
</html>
You have multiple problems here. First is that the date type for inputs is non-standard, so it won't work in most browsers (IIRC chrome, edge, and iOS safari are the exceptions).
I recommend that you either use a third-party library like jquery-ui-datepicker or use a text input with the validation logic using the html pattern attribute or a js event handler if you have to support desktop safari (which doesn't support the pattern attribute).
Something like <input type="text" pattern="/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/"...
Or if pattern won't work:
var myDateInput = document.getElementById('date-input');
myDateInput.addEventListener('change', function(e) {
if (!(e.target.value.match(dateRegex)) {
//let user know somehow
}
});
You can throttle the handler so that it doesn't fire on successive keystrokes. Also note that even in browsers with the date input type they expect "yyyy-mm-dd" format, so make your regex:
/[0-9]{4}-[0-9]{2}-[0-9]{2}/.

Date of Birth Check using angular

I am new to angular and I am not sure how to work with dates. I have a form with name and date of birth.
Before submission I want to check if the person is older than 18 and show an error message before the form is submitted.
But I donot have access to the dob variable in the form unless it is submitted. In my code I have access to $scope.contact.dob only inside addContact(),( after the date is submitted). How do I do date of birth validations before form submission?
My code snippet is shown below
<form>
<input ng-model="contact.name">
<input ng-model="contact.dob" ng-min="minAge()">
<p ng-show="userForm.birthday.$error.min">Mustatleast 18.</p>
<button ng-click=addContact()></button>
</form>
my controller:
.controller("myctrl", function($scope){
$scope.addContact = fucntion(){
console.log($scope.contact)
$scope.contact.dob
}
$scope.minAge = function () {
var current = new Date();
var minYear = current.getFullYear() - 100;
var min = new Date(minYear,current.getMonth(),current.getDate()).toISOString();
return min;
};
})
In angular, while there is a directive for ng-minlength, there is no built-in-directive ng-min. Take a look at the documentation here.
https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D
Instead of ng-min, use the HTML min attribute.
Your code should look like this
<input ng-model="contact.dob" min="{{minAge()}}">
As for the error messages, you should take a look at ng-messages.

Check if date in field is more than x

I would like to have a function that checks if a date in a field is more than 50 years in the past from todays date. If the date is more than 50 years in the past, a message should be shown, but there should not be any minimum date (maximum years).
I have a form where it is possible to add more fields dynamically (name + birthdate), and every new "form" should show this message under the birthday field if it is more than 50 years in the past.
The warning message under each birthdate field should be something like this (if over 50):
<div class="alert alert-warning">This person is over 50 year. Remember to do...</div>
My html setup:
<label for="id_nested-0-name">Name</label>
<input id="id_nested-0-name" maxlength="200" name="nested-0-name" type="text" />
<label for="id_nested-0-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-0-birthdate" name="nested-0-birthdate" type="date" />
<!-- If nested-0-birthdate is over 50, add html with warning message -->
<!-- New person -->
<label for="id_nested-1-name">Name</label>
<input id="id_nested-1-name" maxlength="200" name="nested-1-name" type="text" />
<label for="id_nested-1-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-1-birthdate" name="nested-1-birthdate" type="date" />
<!-- If nested-1-birthdate is over 50, add html with warning message -->
Edit:
This code works great in chrome, but does not work in safari. Anyone see what could be wrong?
<script type="text/javascript">
$(document).ready(function() {
$(function(){
$("#collapse1 input.dateinput").on("change.dp change keyup paste click propertychange",function (e){
var timediff1 = moment().diff(moment($(this).val()), 'years');
if (timediff1 >= 50 ) {
$('#alert1').remove();
$('#collapse1 .panel-body').append('<div id="alert1">Over 50!</div>');
} else {
$('#alert1').remove();
}
});
});
});
</script>
Using http://eonasdan.github.io/bootstrap-datetimepicker/ for my date picker.
Edit 2:
I was missing data-format="DD/MM/YYYY" on my input. Now everything works!
If you dont mind using moment.js
JSFiddle with demo
boolean isOldGeezer = moment().diff(moment($(this).val()), 'years') > 50;
Three part answer to this question
First you need to get the date 50 years ago. I am using a small hack here. You can find better techniques in StackOverflow.
ago50y = new Date();
ago50y.setFullYear(ago50y.getUTCFullYear()-50);
Second, compare that date when the input changes. The following code uses jQuery.
$('input.dateinput').change(function (event) {
if ($(event.target).val() < ago50y.toJSON().slice(0,10)) {
$('#alert').text('This person is over 50 year. Remember to do...');
} else {
$('#alert').text('');
}
});
Third, invoke the second part whenever you add a new set of inputs. Put the above code in a function and include that in the callback while adding the new set.
http://jsfiddle.net/FA4hJ/

Is it possible to specify a specific date range to validate using Parsley.js

I am using a date picker that has a set range 1999:2005 however I only want from 08-01-1999 to be valid to 07-31-2005 so if the user selects outside of these dates I don't want my form to submit but instead prompt the user to add correct dates, I'm using parsley.js and was wondering if it is possible to add a date range in there to take care of this? If not I can add in my own validation.
You can fake it by using the parsley-beforedate="#elem" and parsley-afterdate="#elem" to refer to hidden, non-submitted fields which have these boundary values in them.
Alternatively, write a custom validator in JavaScript which you apply to these date fields along with the standard date validation. Here's one I wrote to prevent dates in the future. You can adapt it for your date range validation (note: it uses the datepicker routine from jqueryui).
$( '#formUpdate' ).parsley( {
validateIfUnchanged: true,
validators: {
// checks that a date is not in the future
// try needed because datepicker can throw an exception
notfuturedate: function ( fieldValue ) {
try {
var d1 = $.datepicker.parseDate("dd/mm/yy", fieldValue); // convert string to date
} catch (e) {
// if date is invalid, let the date check routine report it
return true;
}
var d0 = new Date(); // today
return (d1<=d0);
}
}
// some other irrelevant lines omitted
});
Having declared this new validator, you just put parsley-notfuturedate="true" on the input field and it works like a built-in parsley validation.
Also, if you are using a datepicker like the jqueryUI one , there are options (minDate, maxDate) to limit the range available.
<input type="text" placeholder="MM/DD/YYYY" required="" data-parsley-required-message="Date is required." data-parsley-pattern="^[0-9]{2}/[0-9]{2}/[0-9]{4}$" data-parsley-pattern-message="Invalid Date." data-parsley-maxdate="12/31/2019" data-parsley-mindate="01/01/2018" data-date-format="MM/DD/YYYY">
<script type="text/javascript">
window.ParsleyValidator
.addValidator('mindate', function(value, requirement) {
// is valid date?
var timestamp = Date.parse(value),
minTs = Date.parse(requirement);
return isNaN(timestamp) ? false : timestamp >= minTs;
}, 32)
.addMessage('en', 'mindate', '<div class="date-error">Date should be greater than or equal to %s</div>');
window.ParsleyValidator
.addValidator('maxdate', function(value, requirement) {
// is valid date?
var timestamp = Date.parse(value),
minTs = Date.parse(requirement);
return isNaN(timestamp) ? false : timestamp <= minTs;
}, 32)
.addMessage('en', 'maxdate', '<div class="date-error">Date should be less than or equal to %s </div>');
</script>

Categories

Resources