I am trying to vallidate age on date input field, if somone age in 18+ then he can vallid if he isn’t a 18+ from field will be error how can i do that?
The following copies a given birthdate into a new constant b18 and varies it by adding 18 years to it. The comparison with the current date then shows whether the person is 18 years old or not.
// const b contains birth date to be tested
document.querySelector("input").addEventListener("input",function(){
const b=new Date(this.value);
const b18=new Date(b.getTime());
b18.setYear(b.getFullYear()+18);
// alternatively you could calculate that "critical birthdate",
// 18 years ago, that makes you an adult today:
const d18=new Date();
d18.setYear(d18.getFullYear()-18);
console.log(new Date()>b18,d18>b);
})
<input type ="date" value="2003-08-29">
You can do this:
<input id="age" type="number" />
let age = document.getElementById('age');
let minAge = 18;
age.onchange = () => {
if(!age.value >= minAge){
age.style.border = "1px solid red";
} else if(age.value >= minAge) {
age.style.border = "1px solid green";
}
}