Knockout JS Validation for Date of Birth less than 18
Clash Royale CLAN TAG#URR8PPP
Knockout JS Validation for Date of Birth less than 18
Need help in building a function for my Project which will disable anybody from entering the date of birth less than 18 in the date of birth field.
A validation will work !! just need help in building a validation
htmlcode
<label>Date of Birth <span class="red-asterisk">*</span></label>
<input type="text" id="DOB" name="DateOfBirth" placeholder="  dd/mm/yyyy" data-bind="datePicker : Model.DateOfBirth, dateTimePickerOptions : format: 'DD/MM/YYYY', maxDate: (new Date()).addDays(-6573), useCurrent : false" />
js file code
self.Model.DateOfBirth = ko.observable().extend(
date: true,
required:
params: true,
message: "Please enter a date"
);
where shall I change the code for validation or showing a validation age less than 18 years old not allowed to sign in?
I tried it doesn't help much !! :( can you please help me again...
– Rahul Singh Kamboj
Aug 1 at 2:15
There are a couple ways of doing so, you can either opt for disabling the input field or else implement the extender functionality and then use that implementation. It is very simple and easy to implement the extender.
– Koshux
Aug 6 at 7:34
1 Answer
1
You need to create knockout custom rule as follows
ko.validation.rules["DateValidation"] =
validator: function (val)
var ageDifMs = Date.now() - val.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
var year = Math.abs(ageDate.getUTCFullYear() - 1970);
return (year < 18);
,
message: " "
;
ko.validation.registerExtenders();
then you can add to your extend
self.Model.DateOfBirth = ko.observable().extend(
date: true,
required:
params: true,
message: "Please enter a date"
,
DateValidation:
message: "Override message"
);
Will you please elaborate more what code should i right starting from todays date to validate that at present the person in 18years and older
– Rahul Singh Kamboj
Aug 6 at 2:15
ko.validation.rules["DateValidation"] = validator: function (val) if (Year>=2000) alert('Date Validated 18 Years and Above'); return true; // custom logic for date check and return true or false else , message: " " ;
– Rahul Singh Kamboj
Aug 6 at 2:15
updated answer with logic to calculate age
– jjj
Aug 6 at 7:20
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Have you seen this example from the docs?
– JohnnyHK
Aug 1 at 1:18