我有模型:
[Validator(typeof(RegisterValidator))]
public class RegisterModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ListOfCategoriess { get; set; }
}
和模型验证器:
public class RegisterValidator:AbstractValidator<RegisterModel>
{
public RegisterValidator(IUserService userService)
{
RuleFor(x => x.Name).NotEmpty().WithMessage("User name is required.");
RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required.");
RuleFor(x => x.Email).EmailAddress().WithMessage("Invalid email format.");
RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required.");
RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage("Please confirm your password.");
}
}
我有验证器工厂,应该解决依赖关系:
public class WindsorValidatorFactory : ValidatorFactoryBase
{
private readonly IKernel kernel;
public WindsorValidatorFactory(IKernel kernel)
{
this.kernel = kernel;
}
public override IValidator CreateInstance(Type validatorType)
{
if (validatorType == null)
throw new Exception("Validator type not found.");
return (IValidator) kernel.Resolve(validatorType);
}
}
我有 IUserService,它有方法
IsUsernameUnique(string name)
和 IsEmailUnique(string email)` 并想在我的验证器类中使用它(模型只有在它具有唯一的用户名和电子邮件时才有效)。更新
最佳答案
1) how to use my service for validation?
您可以使用
Must
规则:RuleFor(x => x.Email)
.NotEmpty()
.WithMessage("Email is required.")
.EmailAddress()
.WithMessage("Invalid email format.")
.Must(userService.IsEmailUnique)
.WithMessage("Email already taken");
2) is it possible to register multiple Regular Expression Rules with different error messages? will it work on client side? (if no, how to create custom validation logic for it?)
不,每个属性只能有一种验证类型
if no, how to create custom validation logic for it?
您可以使用 Must 规则:
RuleFor(x => x.Password)
.Must(password => SomeMethodContainingCustomLogicThatMustReturnBoolean(password))
.WithMessage("Sorry password didn't satisfy the custom logic");
3) is validation on server side will work automatically before model pass in action method, and it is enough to call ModelState.IsValid property, or I need to do something more?
是的,一点没错。您的 Controller 操作可能如下所示:
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay the view so that the user
// can fix his errors
return View(model);
}
// at this stage the model is valid => process it
...
return RedirectToAction("Success");
}
更新:
4) is it possible to access to all properties of model when validate some property? (for example I want to compare Password and ConfirmPassword when register)
是的当然:
RuleFor(x => x.ConfirmPassword)
.Equal(x => x.Password)
.WithMessage("Passwords do not match");
关于asp.net-mvc - Fluent 验证自定义验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9367096/