asp.net-mvc - Fluent 验证自定义验证规则

标签 asp.net-mvc asp.net-mvc-3 fluentvalidation

我有模型:

[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)` 并想在我的验证器类中使用它(模型只有在它具有唯一的用户名和电子邮件时才有效)。
  • 如何使用我的服务进行验证?
  • 是否可以使用不同的错误消息注册多个正则表达式规则?它会在客户端工作吗? (如果没有,如何为其创建自定义验证逻辑?)
  • 服务器端的验证是否会在模型传入 Action 方法之前自动工作,调用 ModelState.IsValid 属性就足够了,还是我需要做更多的事情?
    更新
  • 验证某些属性时是否可以访问模型的所有属性? (比如我想在注册时比较Password和ConfirmPassword)
  • 最佳答案

    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/

    相关文章:

    javascript - JQuery 将“null 参数传递给 MVC Controller 方法”

    dependency-injection - ASP.NET MVC 3 RC 中的 MvcServiceLocator 在哪里?

    asp.net-mvc - 如何使用 FluentValidation 在客户端验证日期?

    fluentvalidation - 如何在 FluentValidation 中注册多个程序集的验证器?

    c# - 将米转换为公里并在 Viewmodel 中格式化值

    c# - ASP.NET MVC 是不是 Url.IsLocalUrl() 的功能不正确?

    asp.net-mvc - MVC 3 - 在 View 中显示字典中的值

    c# - ASP.Net web api 后操作参数总是为空

    c# - 使用 Controller 依赖注入(inject)的具有多个存储库的主从 View

    c# - 测试 FluentValidation ChildRules