Vue js & validate DOB is within a range? - validation

Using Vue js and v-validate how can I determine if the date of birth is greater than 21 and less then 55 years old? Any help is greatly appreciated.

import * as moment from "moment";
let birthday = moment(moment.now()).diff(moment(this.user.day + this.user.month + this.user.year, "DD.MM.YYYY"),"years");
if(birthday > 21 && birthday < 55) {
// do next steps
}
Moment(npm install moment) is used to parse, manipulate & display dates and times in JavaScript. moment.now() will give the present date and assuming you have three fields for day, month and year in different variables, format it and use the diff function to find the age.

The example from Madhuri works for me but i change the input as hard coded string.
enter code here let birthday = moment(moment.now()).diff(moment('01.01.1990', "DD.MM.YYYY"), "years");
if(birthday >= 20 && birthday <=70 ){
return birthday;
}
}

I solved it with with value from form input which works for me.
checkBirthday(){
const birthDayDate = document.getElementById("birthdate").value;
const age = moment().diff(birthDayDate, "years");
// let birthday = moment(moment.now()).diff(moment('01.01.1990', "DD.MM.YYYY"), "years");
if(age >= 18 && age <=74 ){
return age;
}
},

Related

Carbon setTestNow function is not working

I am working on dates in Laravel. I have to set dates for patient future injections.
To keep it simple, let's suppose today is 13-03-2019 (Wednesday).
I created first date as:
$firstDate = Carbon::create(2019,03 ,18, 12); // The day is Monday
// set date
Carbon::setTestNow($firstDate);
Now I want the next two appointments should be on Wednesday and Friday. So I again set the dates as follow:
// set second date
$secondDate = new Carbon('Wednesday');
Carbon::setTestNow($secondDate);
// set thirdDate
$thirdDate = new Carbon('Friday');
Carbon::setTestNow($thirdDate);
According to above example the output should be:
2019-03-18
2019-03-20
2019-03-22
But the problem is that it outputs the first set date correct but print the 2nd and 3rd date wrong as it considers 'Wednesday' of next week as today's date.
So the Output print as:
2019-03-18
2019-03-13
2019-03-14
I have spent a lot of time on it, I would appreciate if anyone of you people could help me in this.
I would appreciate if anyone guides me where I am going wrong.
Thanks.
As the setTestNow() function was not working for 2nd and third date/days, so I first get all three required days then convert them to 'dayOfWeek' which returns day number (Sunday 0, Monday 1 and so on...). I subtracted the first day from second and third day and then finally add these days to the date that i get from the datepicker.
// set the start date
if( $visitstart_date != null && $visitstart_date != '') {
Carbon::setTestNow($visitstart_date);
} else {
Carbon::setTestNow();
}
if($perweek_visit1_day != '')
{
//Get first selected day number
$firstDay = Carbon::parse($perweek_visit1_day)->dayOfWeek;
$perweek_visit1_dayDate = Carbon::now();
}
if($perweek_visit2_day != '')
{
//Get second day numer
$secondDay = Carbon::parse($perweek_visit2_day)->dayOfWeek - $firstDay;
$perweek_visit2_dayDate = Carbon::now()->addDays($secondDay);
}
if($perweek_visit3_day != '')
{
//Get third day number
$thirdDay = Carbon::parse($perweek_visit3_day)->dayOfWeek - $firstDay;
$perweek_visit3_dayDate = Carbon::now()->addDays($thirdDay);
}

Why does this Java code have this age validation date comparison?

Here is a response to a question about calculating age in Java.
/**
* This Method is unit tested properly for very different cases ,
* taking care of Leap Year days difference in a year,
* and date cases month and Year boundary cases (12/31/1980, 01/01/1980 etc)
**/
public static int getAge(Date dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
int age = 0;
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if ( (birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) ||
(birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH ))){
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
}else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
(birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
age--;
}
return age;
}
This code works just fine, but why does it have this comparison:
(birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3)
I've gone so far as to create a giant spreadsheet of all the day differences in a year to try to see what cases it might be covering, but I don't see anything that the other comparisons don't cover. Can anyone explain the purpose behind including this comparison? Is it more efficient in some way?
Following code example from ThreetenBP (backport of Java-8) supports the statement that a day-of-year-check is unnecessary:
#Override
public long until(Temporal endExclusive, TemporalUnit unit) {
LocalDate end = LocalDate.from(endExclusive);
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case DAYS: return daysUntil(end);
case WEEKS: return daysUntil(end) / 7;
case MONTHS: return monthsUntil(end);
case YEARS: return monthsUntil(end) / 12;
case DECADES: return monthsUntil(end) / 120;
case CENTURIES: return monthsUntil(end) / 1200;
case MILLENNIA: return monthsUntil(end) / 12000;
case ERAS: return end.getLong(ERA) - getLong(ERA);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.between(this, end);
}
[...]
private long monthsUntil(LocalDate end) {
long packed1 = getProlepticMonth() * 32L + getDayOfMonth(); // no overflow
long packed2 = end.getProlepticMonth() * 32L + end.getDayOfMonth(); // no overflow
return (packed2 - packed1) / 32;
}
The line case YEARS: return monthsUntil(end) / 12; (the expressions birthday.until(today, YEARS) and YEARS.between(birthday, today) are equivalent - one delegating to other) exploits the same algorithm as following reduced code cited by the OP and does not refer to any day-of-year-check:
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
if (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH)) {
age--;
}else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH )) &&
(birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH ))){
age--;
}
The question arises: Why the day-of-year-check?
a) the poster had originally taken the day-of-year-idea seriously and then forgotten to clean up in a later version
b) the poster hopes to "improve" the performance
Following Java-8-code demonstrates the problem of day-of-year-based algorithm if taken seriously and as complete version (the choice of library is not relevant here, only the algorithm matters):
LocalDate birthday = LocalDate.of(2001, 3, 6);
LocalDate today = LocalDate.of(2016, 3, 5); // leap year
int age = today.getYear() - birthday.getYear();
if (birthday.getDayOfYear() > today.getDayOfYear()) {
age--;
}
System.out.println("age based on day-of-year: " + age); // 15 (wrong)
System.out.println("age based on month and day-of-month: "
+ ChronoUnit.YEARS.between(birthday, today)); // 14 (correct)
Conclusion:
The proposed day-of-year-clause you had cited is only noise since the rest of the algorithm corresponds to what Java-8 does. Maybe the day-of-year-check originates from some earlier day-of-year-based versions of proposed code and had not been cleaned up yet.
In order to answer your last question: An unnecessary check like this is not good resp. efficient in terms of performance (although we talk here about micro-optimization).

How can I make a CakePHP 3 time object remain consistent between AJAX and PHP?

When I load a page with a Time object and echo it out on the page through PHP, I get this:
<?= $user->last_login ?>
// 12/30/14, 5:21 pm
When I load data through ajax, it's returned to me like this:
console.log(response.user.last_login);
// 2014-12-30T17:21:31+0000
I haven't set anything different from the default CakePHP 3 setup, and I need events that are added to the page (returned via ajax) to be in the same time format as events that were pulled on page load (return via PHP).
The default output in string format for Time objects is controlled by the setToStringFormat method http://book.cakephp.org/3.0/en/core-libraries/time.html#setting-the-default-locale-and-format-string
It is a good practice to not hardcode a format there, but to only change the current locale so that the right format is selected for you,
But the format that is used to encode to json is not possible to control it via configuration as it is a standard that dates should be presented in such format when encoded in a JSON API. Instead, what you can do is alter the jsonSerialize method in your User entity:
public function jsonSerialize() {
$toEncode = parent::jsonSerialize();
return ['last_login' => (string)$this->last_login] + $toEncode;
}
What it does is converting to string the last_login property before it is encoded to json. Converting to string will then use the globally configured toString format.
You can convert the format of the date using the javascript Date object
JSFiddle
var date = new Date(response.user.last_login)
//returns a timestamp of 1419960091000
var n = date.getTime();
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
//increment the month by 1 as it starts from 0
var year = date.getFullYear();
year = year.toString().substr(2,2);
//this removes the first 2 characters to give yy, remove the above line for yyyy
var hours = date.getHours();
var minutes = date.getUTCMinutes();
var period='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12){
hours=hours%12;
//remove the above line for 24 hour format
period='pm';
}
Now you can piece together the date in the required format
var last_login = day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ' ' + period;
//gives 30/12/14 5:21 pm
Hope this helps!

Rails Auto-populate form field based off of date input

I have a Rails 3.2.18 app where in my form I have a field for age (int) and date of birth (datetime). I will be using a simple jQuery date picker to select the DOB.
Here's what I want to happen.
The first field is the DOB (Date of birth). I want to select that, and as soon as it's selected I'd like to calculate the age and automatically fill the age field based off of that selection.
I think I can do it somehow by creating a method on the model that calculates the age, but I'm not sure how to populate it in the age field. Perhaps some Javascript or something?
Any help would be greatly appreciated.
Below is a method I wrote for another app that calculates age based on DOB and can be used in a view:
def age(dob)
now = Time.zone.now.to_date
now.year - patient_dob.year - ((now.month > patient_dob.month || (now.month == patient_dob.month && now.day >= patient_dob.day)) ? 0 : 1)
end
What you are suggesting is not possible to do in Ruby. You can use JavaScript.
It's not possible to calculate the age, based on user input, without first traveling to the server, calculating the age, and then rendering the result to the client. The model has no knowledge of the date that the user puts in; this is, unless you submit the form, of course.
It's possible to submit the form via Ajax. For example, some sites let you fill in a zip code, and then they prefil the address for you. What is really happening is, behind the scenes, the browser is sending an ajax request to a server that returns an address.
In your case you shouldn't have to do that since calculating the age in JavaScript is very easy. It's also quicker to do it on the client since it saves you the round trip to the server.
Take a look at this answer which shows you how to calculate a persons age based on an input date.
If you are using Rails you will likely be using jQuery. In which case you can do something like this:
$('#date_input').on('change', function () {
date = $(this).val();
age = getAge(date);
$('#age_input').val(age);
});
# This is taken directly from this answer: https://stackoverflow.com/a/7091965/276959
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Then, on the server you may want to recalculate the age before you save the data into the database. This is because nothing stops the user from submitting a false age directly. Either by filling it in, or by altering the DOM.
class Person
before_save :set_age
private
def set_age
self.age = # Calculate age here.
end
end
See this answer on how to calculate age using Ruby, which looks identical to the code you have in your question.
This is a more client side javascript way to achieve this with date accuracy using server.
In your rails view when parent page loads
<%= javascript_tag do%>
var currDate = new Date('<%= Date.today%>');
<%end%>
In your js file (i assumed date-picker to be the input selected using date picker.)
function calcAge(dateString) {
var birthDate = new Date(#('date_picker').val());
var age = currDate.getFullYear() - birthDate.getFullYear();
var m = currDate.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && currDate.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Then just need to call calcAge on date selected event and the
return age;
can change to set value on an input field
$('#ageField').val(age);

jQuery validate credit card exp date as future date

I can't seem to get this right, I can get it to catch a past date, but not return true on future date.I just need to validate my form's Credit Card Expiration Date as being in the future, this isn't working, any ideas? the date has to be in the format MM/YYYY with a "/" in between them.
$.validator.addMethod(
"FutureDate",
function(value, element) {
var startdatevalue = (.getMonth/.getYear);
return Date.parse(startdatevalue) < Date.parse($("#ExpirationDate").val());
},
"End Date should be greater than Start Date."
);
You're not actually getting it to catch a past date. If you're passing a date like this "11/2010" to your Date.parse(), it is returning NaN (or Not a Number) which is the logical equivalent to returning false.
Try doing this to see what I mean:
alert( Date.parse('11/2010') );
If you add a day number, it should work. Something like:
var startdatevalue = '11/1/2010';
Of course, this example uses a hard coded date. If the values are stored as 11/2010, you could try something like this:
// Get the index of the "/"
var separatorIndex = value.indexOf('/');
// Add "/1" before the separatorIndex so we end up with MM/1/YYYY
var startDate = value.substr( 0, separatorIndex ) + '/1' + value.substr( separatorIndex );
// Do the same with the expiration date
var expDate = $("#ExpirationDate").val();
separatorIndex = expDate.indexOf('/');
expDate = expDate.substr( 0, separatorIndex ) + '/1' + expDate.substr( separatorIndex );
// Return the comparison
return Date.parse(startDate) < Date.parse(expDate);

Resources