Please check out this excellent post on creating a custom validation. Adding a second type of validation is cleaner as it doesn't require you to edit existing code.
In your case it would be something like
Validation.add('validate-dob-18','You are not 18',function(value){
[...]
calculate nr of years
[...]
if(years > 18)
{
return true;
}
return false;
});
I would suggest also adding PHP validation as Javascript validation as anything but secure.
Also, to work more easily with dates and times check out momentjs.
Excellent question!
You don't need jQuery for this. You can do this with the built-in Magento form validator. First the javascript to set up the form for validation must be placed in your form template:
<script type="text/javascript">
var myForm= new VarienForm('[your form id]', true);
</script>
Now prepare your form fields by adding the appropriate css classes.
Cannot have number greater than 9.99
<input type="text" class="required-entry validate-digits-range digits-range-0-9.99"/>
No spaces in the fields
<input type="text" class="required-entry validate-alphanum"/>
That's it! For the more specific use cases you'll have to add custom validation rules:
Only number fields need to have .00 to validate 1 to 1.00
Validation.add('validate-float','Input must be in the form of 0.00',function(v){
return Validation.get('IsEmpty').test(v) || (!/\./.test(v));
});
Which then is validated with the following:
<input type="text" class="required-entry validate-float"/>
Letters need to be uppercase
This one is similar, the regex must test for a range of uppercase:
Validation.add('validate-uppercase','Input must be in uppercase',function(v){
return Validation.get('IsEmpty').test(v) || (!/^[A-Z]+$/.test(v));
});
And used like:
<input type="text" class="required-entry validate-uppercase"/>
Best Answer
As far as I know, our model usually derives from
\Magento\Framework\Model\AbstractModel
class. So, we can validate the data before saving it by using Observer or overloadbeforeSave
method in our Model.