Checking the entry age using the moment. js

I use Moment.js to check for ages over 18 years.

My code is:

function validate(date){
var eighteenYearsAgo = moment().subtract("years", 18);
var birthday = moment(date);

if (!birthday.isValid()) {
    return "invalid date";    
}
else if (eighteenYearsAgo.isAfter(birthday)) {
    return "okay, you're good";    
}
else {
    return "sorry, no";    
}

}

I have an input

<input type="text" name"SocialSecurityNumber">

How can I attach this script to the input so that it checks the age, every time someone leaves the input field? (Blur)

+4
source share
1 answer
<input type="text" name="SocialSecurityNumber" onblur="return validate(this.value);" />

Personally, I use jquery validator and made this method:

$.validator.addMethod("minage", function(value,element,argument){
  var age = moment(value);
  var now = moment();
  return this.optional(element) || now.diff(age,'years') >= argument;
}, $.format("Applicant must be at least {0} years old.")); 
0
source

Source: https://habr.com/ru/post/1528943/


All Articles