Formvalidation.io - Validate fields based on value of other fields

3.3k views Asked by At

I have been trying to find the solution to this for some time now but I am not having much luck. I'm sure the solution is simple so thanks in advance for the help!

I am using the formvalidation io plugin and have it working perfectly on multiple forms. I have another large form that I want to validate a customer's name. I have 3 fields (CompanyName, FirstName, & LastName) in the form and I want to validate based on the following rules:

  • CompanyName or FirstName & LastName Required
  • If no Company Name is entered the both FirstName & LastName are required
  • If CompanyName is entered then FirstName & LastName are not required but either can have a value

Hopefully that all makes sense. I have figured out how to use a hidden field to require both FirstName and LastName to be entered (Valdiating multiple inputs as one). I'm sure this will require some sort of conditional validation (Conditional Validation) to accomplish this but I'm not sure how to implement.

Does anyone have any experience accomplishing something like this? As I said, thanks in advance.

3

There are 3 answers

0
Marcos Adriano On

In your js code you can set "data-fv-excluded" attribute true or false depending on the fields you want to validade for example:

if(document.getElementById('firstname').value && document.getElementById('lastname').value){
    document.getElementById('companyname').setAttribute("data-fv-excluded", "true");
}

The validator will ignore your fields with data-fv-excluded="true"

0
AmitB10 On

Yes you can do that using callback validator. Example for company name:

companyname: {
                validators : {
                    callback: {
                        message: 'companyname is required',
                        callback: function(value, validator, $field) {
                            if(document.getElementById('firstname').value && document.getElementById('lastname').value){
                                return true;
                            }
                            return false;
                        }
                    }
                }
            }
0
Zahra Badri On

You can use like this. It work fine for me:

companyname: {
                validators: {
                    callback: {
                        message: 'Please Enter first name and last name when company name is empty',
                        callback: function(input) {
                            var companyName = input.value;
                            if (companyName === '') {

                        var firstName = document.getElementById('first_name').value;
                        var latsName = document.getElementById('last_name').value;

                        return (firstName !== '')&&(latsName !== '');
                    }

                    return true;
                }
            }
        }
    }
}