加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:33:04 所属栏目:asp.Net 来源:网络整理
导读:我有模特: [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; }} 和模型验证
我有模特:
[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");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读