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(字符串电子邮件)`并且想在我的验证器类中使用它(模型只有在具有唯一用户名和电子邮件时才有效). >如何使用我的服务进行验证? 解决方法
您可以使用必须规则: RuleFor(x => x.Email)
.NotEmpty()
.WithMessage("Email is required.")
.EmailAddress()
.WithMessage("Invalid email format.")
.Must(userService.IsEmailUnique)
.WithMessage("Email already taken");
不,每个属性只能有一种验证类型
您可以使用必须规则: RuleFor(x => x.Password)
.Must(password => SomeMethodContainingCustomLogicThatMustReturnBoolean(password))
.WithMessage("Sorry password didn't satisfy the custom logic");
是的,一点没错.您的控制器操作可能如下所示: [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");
}
更新:
当然是: RuleFor(x => x.ConfirmPassword)
.Equal(x => x.Password)
.WithMessage("Passwords do not match"); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – 应用程序池循环如何影响ASP Net会话状态?
- asp.net-mvc – 如何在控制器中显示警报消息
- asp.net-mvc-2 – 如何在Asp.net MVC 2中使用Base ViewMode
- asp.net-mvc – 允许使用数字中的点和逗号,而不仅仅是小数
- asp.net-mvc-4 – 如何在MVC 4 w / default simplemembersh
- asp.net-mvc-3 – 有没有办法使用@ Html.HiddenFor获取完整
- asp.net – MVC 3 htmlhelper的扩展方法来包装内容
- ASP.NET 5中的子域路由
- asp.net – 想要在ModalPopExtender之上显示Update Progres
- asp.net-mvc – ASP.NET MVC报告
- asp.net-mvc – 带tab-id的RedirectToAction()
- asp.net-mvc – 适用于MVC 2 beta 2的MicrosoftM
- RavenDB ASP.NET会话提供程序?
- asp.net-mvc – 如果ActionResult未更改,则将MVC
- asp.net-mvc – asp.net mvc – 需要存储当前请求
- asp.net – 在Web.config中是否可以在指定目录中
- asp.net-mvc – 如何使用枚举值填充下拉列表?
- 使用ASP.NET MVC在JS文件中设置jQuery的ajax url
- 点击图片,AJAX删除后台图片文件的实现代码(asp.n
- asp.net – 错误:“填充:SelectCommand.Connec
