foxhound87 / mobx-react-form

Reactive MobX Form State Management
https://foxhound87.github.io/mobx-react-form
MIT License
1.09k stars 129 forks source link

Custom validation rules don't run on empty fields. #269

Closed benjamingeorge closed 7 years ago

benjamingeorge commented 7 years ago

When creating a custom rule, they only run if there is a value in the field. Which is a problem for custom rules that are of the "require_if" type. Creating a simple mock custom rule using the "required" code you will see that in the console "validating" is only logged if there is a value in the input field, not empty.

const rules = {
    my_custom_rule: {
        fn: function(val) {
            var str;

            console.log('validating');

            if (val === undefined || val === null) {
              return false;
            }

            str = String(val).replace(/\s/g, "");
            return str.length > 0 ? true : false;
        },
        message: "The :attribute is required"
    }
};

export default $validator =>
    Object.keys(rules).forEach(key =>
        $validator.register(key, rules[key].fn, rules[key].message));

then using it

const fields = [{
        type: 'text',
        name: "shortName",
        label: "Short Name",
        placeholder: "Short Name",      
        rules: "my_custom_rule",
        options: {
            validateOnChange: true,
        }
    }]
foxhound87 commented 7 years ago

I checked my package's code but I think it is ok, I don't call that function directly in my code. It seems related to the validatorjs package because it handles the execution of that function. I don't know if it is a bug or it deliberately forces you to use the required rule keyword to check the presence of the value. We should open the issue there on their repo.

benjamingeorge commented 7 years ago

ok thanks. I went the custom validator route and that seemed solve my issue.

foxhound87 commented 7 years ago

@benjamingeorge what do you mean?

benjamingeorge commented 7 years ago

something like

{
        type: 'text',
        name: "shortName",
        label: "Short Name",
        placeholder: "Short Name",
        rules: "string|max:60",
        validators: [requireIfMaxExceeds('name', 60)],
        options: {
            validateOnChange: true,
        }
    }
foxhound87 commented 7 years ago

Great!