userfrosting / fortress

A schema-driven system for elegant whitelisting, transformation and validation of user input on both the client and server sides from a unified set of rules.
Other
25 stars 9 forks source link

Validating field y only when field x is not null / conditional validations #12

Open spurgeonbj opened 8 years ago

spurgeonbj commented 8 years ago

Hi,

Greetings!

Not sure if this is the right place to request help regarding this.

Can you kindly, specify how to specify rules for field x and y,

that field y is required if field x is not null.

Thanks!! Warm regards and gratitude, Spurgeon

alexweissman commented 8 years ago

Hmm, that is a tricky one. Fortress doesn't have any rules like this at the moment, so you will just need to implement that logic manually in your controller.

spurgeonbj commented 8 years ago

Hi Alex!

Thanks for the kind and quick response!

May be this could be a common, simpler use case.

let's say in a drop down or list, 'Other' is selected. Then, the related details field should be made required.

jquery validation supports this as documented at https://jqueryvalidation.org/required-method (Example: Makes details required only if #other is checked.)

$( "#myform" ).validate({ rules: { details: { required: "#other:checked" } } });

Hope we'll get this fortress!

Thanks once again! warm regards and gratitude, Spurgeon

alexweissman commented 8 years ago

So, we would need a way to generalize this across client- and server-side rules (:checked is a jQuery selector and doesn't really have any meaning on the server side). What do you propose?

spurgeonbj commented 8 years ago

in our usecase, checked is not needed, we just need to see if the first field is not null.

As a newbie to fortress am not sure about what can be proposed.

However, I guess we should be able to use native jquery validate constructs in page specific block of twig template of userfrosting to handle this.

Thanks! :-)

alexweissman commented 8 years ago

I think the right way to do this would be to introduce "conditional rules" - rules that are only applied if a certain condition is met:

    "field_y" : {
        "validators" : {
            "required" : {
                "condition": "field_x != null",
                "message" : "ACCOUNT_SPECIFY_EMAIL"
            }
        }
    }

Of course, then we would need to be able to parse the expressions in condition to generate the appropriate client- and server-side logic.