Reputation: 531
i use ServiceStack
build a web service,
this is my validator
code:
public class AccountValidator : AbstractValidator<AccountModel>
{
public AccountValidator()
{
//only for post
RuleSet(ServiceStack.ApplyTo.Post, () =>
{
RuleFor(s => s.Password).Length(30);
});
}
}
Service code
public object Post(Account req) {
AccountModel model = req.ConvertTo<AccountModel>();
var result = this.Validator.Validate(model);
if (result.IsValid)
{
//is aways true
}
throw result.ToException();
}
the Account.Password is "abc" ,way the result.IsValid
is true
?
Upvotes: 1
Views: 319
Reputation: 21501
The result is always true
because the ApplyTo.Post
condition in your validator only applies to rules that are validated on the Request DTO. The ApplyTo
conditions don't work for FluentValidation that is invoked manually. See the Validation Documentation.
But given that you are converting the Account
into an AccountModel
you could use the ValidationFeature
plugin to check the validation of Account
before converting it to an AccountModel
.
Thus:
public class AccountValidator : AbstractValidator<Account>
{
public AccountValidator()
{
RuleSet(ApplyTo.Post, () => RuleFor(s => s.Password).Length(30));
}
}
// Account will be validated on POST
public object Post(Account req)
{
// Account is valid coming into the request
AccountModel model = req.ConvertTo<AccountModel>();
// Is it not safe to assume the model is valid, because Account is valid?
}
Upvotes: 2