asp.net-mvc – 流畅的验证自定义验证规则

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 流畅的验证自定义验证规则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有模特:
[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(字符串名称)和IsEmailUnique(字符串电子邮件)`并且想在我的验证器类中使用它(模型只有在具有唯一用户名和电子邮件时才有效).

>如何使用我的服务进行验证?
>是否可以使用不同的错误消息注册多个正则表达式规则?它会在客户端工作吗? (如果没有,如何为它创建自定义验证逻辑?)
>服务器端的验证是否会在模型传入操作方法之前自动工作,并且它足以调用ModelState.IsValid属性,或者我需要做更多的事情?
UPDATE
>验证某些属性时是否可以访问模型的所有属性? (例如我想在注册时比较密码和ConfirmPassword)

解决方法

1) how to use my service for validation?

您可以使用必须规则:

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?

您可以使用必须规则:

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?

是的,一点没错.您的控制器操作可能如下所示:

[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相关文章