根据 ASP.NET MVC 中的条件设置必填字段验证
Set Required Field Validation based on condition in ASP.NET MVC
我想根据 ASP.NET MVC 中的条件执行验证。
我有相同的页面和模型用于插入和更新记录,现在我想根据条件设置必填字段。
插入时,EmployeeCode 是必需的,但在更新时我不想设置 EmployeeCode 是必需的。
如何在 asp.net mvc 中像这种情况一样执行验证?
您可以通过在 ViewModel 上实现 IValidatableObject
来添加自定义验证逻辑。
public class MyViewModelThatMixesTwoUsecases : IValidatableObject {
public string EmployeeCode { get; set; }
public bool IsCreateUsecase { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (IsCreateUsecase && string.IsNullOrWhiteSpace(EmployeeCode)) {
yield return new ValidationResult(
"EmployeeCode is required for create usecase",
new[] {"EmployeeCode"}
);
}
}
}
在控制器中,通过调用 ModelState.IsValid
来测试您的模型是否有效。
您可以使用 Fluent 验证。
RuleFor(x => x.EmployeeCode)
.Must((o,e) =>
{
if (o.Id > 0)
{
return true;
}
return !string.IsNullOrEmpty(o.EmployeeCode);
})
.WithMessage("Employee code is required");
您也可以使用 Dataannotation 验证来实现此目的。让我知道您使用的是哪个库以及版本。
使用CustomeValidationAttribute
.
首先,用 [CustomValidationAttribute]
修饰您的 属性,指定验证方法。例如
[CustomValidation(typeof(YourModel), nameof(ValidateEmployeeCode))]
public string EmployeeCode { get; set; }
ValidateEmployeeCode
必须是public、static、returnValidationResult
,并接受一个对象作为第一个参数,或者[=30=的具体类型] 正在验证中。它还可以接受 ValidationContext
作为第二个参数,它具有有用的属性,例如正在验证的实例和 属性.
的显示名称
然后该方法会根据条件检查值是否为空,并显示 return 一个 ValidationResult.Success
或一个新的 ValidationResult
并显示错误消息在视图中调用 Html.ValidationMessageFor()
给用户。您可以使用记录 ID 的值作为标志来了解它是新记录还是更新记录。
我想根据 ASP.NET MVC 中的条件执行验证。
我有相同的页面和模型用于插入和更新记录,现在我想根据条件设置必填字段。
插入时,EmployeeCode 是必需的,但在更新时我不想设置 EmployeeCode 是必需的。
如何在 asp.net mvc 中像这种情况一样执行验证?
您可以通过在 ViewModel 上实现 IValidatableObject
来添加自定义验证逻辑。
public class MyViewModelThatMixesTwoUsecases : IValidatableObject {
public string EmployeeCode { get; set; }
public bool IsCreateUsecase { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (IsCreateUsecase && string.IsNullOrWhiteSpace(EmployeeCode)) {
yield return new ValidationResult(
"EmployeeCode is required for create usecase",
new[] {"EmployeeCode"}
);
}
}
}
在控制器中,通过调用 ModelState.IsValid
来测试您的模型是否有效。
您可以使用 Fluent 验证。
RuleFor(x => x.EmployeeCode)
.Must((o,e) =>
{
if (o.Id > 0)
{
return true;
}
return !string.IsNullOrEmpty(o.EmployeeCode);
})
.WithMessage("Employee code is required");
您也可以使用 Dataannotation 验证来实现此目的。让我知道您使用的是哪个库以及版本。
使用CustomeValidationAttribute
.
首先,用 [CustomValidationAttribute]
修饰您的 属性,指定验证方法。例如
[CustomValidation(typeof(YourModel), nameof(ValidateEmployeeCode))]
public string EmployeeCode { get; set; }
ValidateEmployeeCode
必须是public、static、returnValidationResult
,并接受一个对象作为第一个参数,或者[=30=的具体类型] 正在验证中。它还可以接受 ValidationContext
作为第二个参数,它具有有用的属性,例如正在验证的实例和 属性.
然后该方法会根据条件检查值是否为空,并显示 return 一个 ValidationResult.Success
或一个新的 ValidationResult
并显示错误消息在视图中调用 Html.ValidationMessageFor()
给用户。您可以使用记录 ID 的值作为标志来了解它是新记录还是更新记录。