Advanced conditional logic with custom javascript functions

CF7 Conditional Fields PRO 1.6.2 introduces the possibility to write your own JavaScript functions to determine whether or not a group should be shown.

Form

Sorry, you are too young to watch dirty pictures. Try decreasing your date of birth.

Hooray! You are older than 18. Here's some explicit content:

    o
   /__o
 _// <
'

Form Code

<label>Date of birth:
[date date-of-birth "2010-04-03"]</label>

[group minus-18]
Sorry, you are too young to watch dirty pictures. Try decreasing your date of birth.

[/group][group plus-18]
Hooray! You are older than 18. Here's some explicit content:
<pre style="font-family:monospace">
    o   
   /__o 
 _// < 
'   
</pre>
[/group]

Conditional Fields

show group if field operator value

plus-18 if date-of-birth function isOlderThan18 
minus-18 if date-of-birth function isYoungerThan18 

In order for the above example to work, you need to create two JavaScript functions – not PHP functions! – called isOlderThan18($field) {} and isYoungerThan18($field) {} in your theme. These functions need to return true or false. Preferably, you need to place these functions somewhere in a custom JS file, or if you must, in your header.php or footer.php, for example before the closing </body> tag in your theme.

The $field parameter passed is the jQuery object of the date field. If you want to access the DOM field directly, you can get it with $field[0].

Here’s the full JavaScript code used to check if the user is older or younger than 18:

<script>

    function isOlderThan18($field) {

        //expected format: yyyy-mm-dd

        var birthdate_str = $field.val();
        var dmy = birthdate_str.split("-");

        if (dmy.length !== 3 ||
            isNaN(dmy[0]) || dmy[0].length!==4 ||
            isNaN(dmy[1]) || dmy[1].length!==2 ||
            isNaN(dmy[2]) || dmy[2].length!==2 )
        {
            return false; //invalid format
        }

        var birthdate = new Date(dmy[0], dmy[1] - 1, dmy[2]);

        if (birthdate === "Invalid Date" || isNaN(birthdate))
        {
            return false; // invalid date
        }

        //at this point the date is valid

        if (calculateAge(birthdate) >= 18) {
            return true; // older than 18
        } else {
            return false; // younger than 18
        }

    }

    function isYoungerThan18($field) {
        return !isOlderThan18($field);
    }

    function calculateAge(birthdate) { // birthday is a date
        var ageDifMs = Date.now() - birthdate.getTime();
        var ageDate = new Date(ageDifMs); // miliseconds from epoch
        return Math.abs(ageDate.getUTCFullYear() - 1970);
    }

</script>