Conditionally run validations
Hey
I have a UserFeedback resource that has questions & answers collected from users who provide feedback in my LiveView app via a
create :provide_feeback
action
When determining whether to get feedback from a user I check if the changeset is valid, i.e. Ash.Changeset.for_create(UserFeedback, :provide_feedback, %{...}, actor: current_user).valid?
When a user if providing feedback, I also validate on change of the form:
This allows me to encapsulate all of the validation logic in the action itself, being:
* User must not have already provided feedback (i.e. UserFeedback with user_id == current_user.id doesn't exist)
* The answer to each question must be less than a configured number of characters
I don't really want to be checking the db for an existing UserFeedback on each keypress when the user is filling out the form, just initially when determining whether to show the form and then when submitting it
I could provide an argument, say: validate_full?
and if false then skip the existence check
Since this pattern might be useful across several actions for the same reason, I wonder if there's a better way to do this or would it be valuable to add?
Thanks!5 Replies
Validations support a where option which takes a list of validations and they are checked before running the main validation. So you could create a validation that checks for that specific argument, or maybe I would use the context to pass this option and use it as a where clause to your exists check
Thanks for the quick reply
I like the idea of having it as an option to the validation so will explore that
I'd think this might be useful as a general option, is it possible to determine whether the changeset is being validated via
Form.validate
automatically or would there have to be some manual involvement (i.e. setting the argument)?Not sure, I've done mostly API stuff, but I think there is nothing special set by AshPhoenix when validating/submitting forms. But we could potentially set something in the context marking it as a form validation/submition
Yeah I guess it's more specific to AshPhoenix so a
skip_when_validating?
flag might not make much sense in general
I'll think a bit more on it and maybe make a GH issue, would you think more appropriate to raise in Ash or AshPhoenix?Validation like this happens most often AshPhoenix but either is fine, we'll route it to the right place if necessary