-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Validating primitive types #184
Comments
That isn't really something that's supported I'm afraid. The whole point of FluentValidation is to validate properties on objects. Technically, you can define rules for primitives like this:
...however, you will find that there are some features that don't work with this approach, and isn't really recommended. |
Similar to this, is there a way to define a set of rules for a primitive type, and reuse that set of rules? For example, if I want to validate the complexity of a password with several checks, but I have multiple models that use those same checks - I would rather not refactor the password component into a complex type. It would be great to group multiple rules into a group and be able to reuse them. I did see rule sets, but those are a bit different. Thanks! |
Yes, you have a couple of options. You can use the approach I documented above, by creating an AbstractValidator instance that acts on strings. The other option is to write an extension that wraps the multiple calls to RuleFor. |
Hi Jeremy, Thanks for the quick response! I've been looking for examples of the second approach, wrapping multiple calls to RuleFor and have not found any. Do you have any advice there? |
Sure, here's an example that chains multiple rules on a string property, within an extension method.
This is actually how all of FV's default validation rules (NotNull, NotEmpty etc) work- they're all extesnions on IRuleBuilder that perform certain actions (usually calling SetValidator to encapsulate within a custom property validator) |
Thanks Jeremy! |
Maintenance / cleanup: Closing this as the question appears to be answered. |
I'm trying to find a way how I can use built-in validators to validate primitive types like strings or ints. For example, I would like to be able to use
EmailValidator
to validate a string value (not a string property of a complex type) by calling something likeValidate
. ButEmailValidator
isIPropertyValidator
, notIValidator
.Any ideas how to use FluentValidation to validate primitive types?
The text was updated successfully, but these errors were encountered: