Asp.net-Mvc

Fluent 驗證自定義驗證規則

  • February 20, 2012

我有模型:

[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. 如何使用我的服務進行驗證?
  2. 是否可以使用不同的錯誤消息註冊多個正則表達式規則?它會在客戶端工作嗎?(如果沒有,如何為其創建自定義驗證邏輯?)
  3. 伺服器端的驗證是否會在模型傳入動作方法之前自動工作,呼叫 ModelState.IsValid 屬性就足夠了,還是我需要做更多的事情? 更新
  4. 驗證某些屬性時是否可以訪問模型的所有屬性?(例如我想在註冊時比較Password和ConfirmPassword)

1)如何使用我的服務進行驗證?

您可以使用以下Must規則:

RuleFor(x => x.Email)
   .NotEmpty()
   .WithMessage("Email is required.")
   .EmailAddress()
   .WithMessage("Invalid email format.")
   .Must(userService.IsEmailUnique)
   .WithMessage("Email already taken");
  1. 是否可以使用不同的錯誤消息註冊多個正則表達式規則?它會在客戶端工作嗎?(如果沒有,如何為其創建自定義驗證邏輯?)

不,每個屬性只能有一種驗證類型

如果沒有,如何為其創建自定義驗證邏輯?

您可以使用 Must 規則:

RuleFor(x => x.Password)
   .Must(password => SomeMethodContainingCustomLogicThatMustReturnBoolean(password))
   .WithMessage("Sorry password didn't satisfy the custom logic");

3)在模型傳入action方法之前,伺服器端的驗證是否會自動工作,呼叫ModelState.IsValid屬性就足夠了,還是我需要做更多的事情?

是的,一點沒錯。您的控制器操作可能如下所示:

[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");
}

更新:

  1. 驗證某些屬性時是否可以訪問模型的所有屬性?(例如我想在註冊時比較Password和ConfirmPassword)

是的當然:

RuleFor(x => x.ConfirmPassword)
   .Equal(x => x.Password)
   .WithMessage("Passwords do not match");

引用自:https://stackoverflow.com/questions/9367096