Custom validation - making other fields required based on a radio button choice


Looking at previous posts about custom validation I got this partially working in javascript, but not all the way.

What I’m trying to do: I have a radio button for user contact preference (email or text). Based on the answer I want to make either email address or phone number mandatory, which neither is on their own.

What I tried: building a rule for the contact preference radio button. Based on the answer, looking at the length of the value for the corresponding choice and throwing an error.

Result: (code below) It worked but only for one of the cases. Based on console.log values I think the issue is that the value of my radio button choice isn’t being updated and triggering the right validation. Does this require a separate onselect or onclick script connected to the submit button?


  lp.jQuery(function($) {

    var ruleID = 'contactMethod';

    //The email field to check
    var emailField = 'email';

    //The phone field to check
    var phoneField = 'phone_number';

    var prefField = 'cpref';

    var message = 'You must enter a value for the contact method you chose.';

    var rules =[prefField];

    $.validator.addMethod(ruleID, function(value, prefField) {

        var emailValue = $('#' + emailField).val();

        var phoneValue = $('#' + phoneField).val();

        if(value === 'Email'){
          var valid = (emailValue.length > 0);
          var valid = (phoneValue.length > 0);
        return valid || (!rules.required && !value);
    }, message);

    rules[ruleID] = true;



Hey there @jiseki_dev!

Thanks so much for sharing your experience so far. I’d be curious to see if any of our @Unbounce-Experts have some insight into this.

You might be right. I’m going to wait for our more technical Community members to chime in before I dive into this further, but I’ll be keeping an eye on this. :eyes: