Wednesday, 23 September 2015

Semantic UI age Validation

We're doing lots with Semantic UI forms and I'm sort of loving and hating their form validation... more loving than hating after discovering the ability to add validation rules!

We need to check ages before submitting a form and, while we check on the server-side, it's always nice to check on the client-side as well! We've implemented a DateTimePicker and restricted the selectable dates within it but the user can still enter an invalid date manually. To validate this using Semantic UI I wrote this simple Validation RUle and added it to $.fn.form.settings.rules:

$.fn.form.settings.rules.age = function(value, age) {
    if(moment(value, "DD/MM/YYYY").isBefore(moment().subtract(parseInt(age, 10), "year"))){
        return true;
        return false;

Like most of the things I write these days it requires Moment.js and to use it simply add a rule like this to your form:

"Birthdate": {
    "identifier" : "Birthdate",
    "rules": [
            "type"   : "age[18]",
            "prompt" : "You need to be at least 18"

This will check to see if the date entered is older than 18 years. To change the number of years simply alter 18.