可选地使用必填字段和 ASP.NET MVC 数据注释
Using Required field optionally with ASP.NET MVC Data Annotation
我在 ASP.NET MVC 项目中使用 EF 数据注释,对于必填字段,我定义了如下所示的字段:
型号:
[Required(ErrorMessage = "Required!");
public string PhoneHome{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneWork{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneMobile { get; set; }
查看:
@Html.TextBoxFor(m => m.PhoneHome)
@Html.ValidationMessageFor(m => m.PhoneHome, null, new { @class = "field-validation-error" })
@Html.TextBoxFor(m => m.PhoneWork)
@Html.ValidationMessageFor(m => m.PhoneWork, null, new { @class = "field-validation-error" })
@Html.TextBoxFor(m => m.PhoneMobile )
@Html.ValidationMessageFor(m => m.PhoneMobile , null, new { @class = "field-validation-error" })
我只想将这些字段中的一个设为必填项(如果用户填写其中一个字段就可以,但是如果他没有填写其中任何一个我想显示一条错误消息并且不让他填写提交表格),但不知道执行此操作的最合适和更智能的方法?我是否应该在提交时使用 JavaScript 检查所有这些字段并显示必要的错误消息?或者我应该只使用数据注释来执行此操作吗?
public class MyModel : IValidatableObject
{
[Required(ErrorMessage = "Required!");
public string PhoneHome{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneWork{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneMobile { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((PhoneHome+PhoneWork+PhoneMobile).Length < 1)
{
yield return new ValidationResult("You should set up any phone number!", new [] { "ConfirmForm" });
}
}
}
好的,我举了个例子。我创建了一个自定义验证属性,其中包含一些参数,例如需要哪些属性以及数量(最小值和最大值)。命名不是最好的,但它完成了工作(未测试)。如果您不关心客户端上的验证,则可以删除 ICIentValidatable(使用 jquery 验证,不显眼...)。
属性是这样制作的:
public class OptionalRequired : ValidationAttribute, IClientValidatable
{
/// <summary>
/// The name of the client validation rule
/// </summary>
private readonly string type = "optionalrequired";
/// <summary>
/// The (minimum) amount of properties that are required to be filled in. Use -1 when there is no minimum. Default 1.
/// </summary>
public int MinimumAmount { get; set; } = 1;
/// <summary>
/// The maximum amount of properties that need to be filled in. Use -1 when there is no maximum. Default -1.
/// </summary>
public int MaximumAmount { get; set; } = -1;
/// <summary>
/// The collection of property names
/// </summary>
public string[] Properties { get; set; }
public OptionalRequired(string[] properties)
{
Properties = properties;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int validPropertyValues = 0;
// Iterate the properties in the collection
foreach (var propertyName in Properties)
{
// Find the property
var property = validationContext.ObjectType.GetProperty(propertyName);
// When the property is not found throw an exception
if (property == null)
throw new ArgumentException($"Property {propertyName} not found.");
// Get the value of the property
var propertyValue = property.GetValue(validationContext.ObjectInstance);
// When the value is not null and not empty (very simple validation)
if (propertyValue != null && String.IsNullOrEmpty(propertyValue.ToString()))
validPropertyValues++;
}
// Check if the minimum allowed is exceeded
if (MinimumAmount != -1 && validPropertyValues < MinimumAmount)
return new ValidationResult($"You are required to fill in a minimum of {MinimumAmount} fields.");
// Check if the maximum allowed is exceeded
else if (MaximumAmount != -1 && validPropertyValues > MaximumAmount)
return new ValidationResult($"You can only fill in {MaximumAmount} of fields");
//
else
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = "Enter your error message here or manipulate it on the client side";
rule.ValidationParameters.Add("minimum", MinimumAmount);
rule.ValidationParameters.Add("maximum", MaximumAmount);
rule.ValidationParameters.Add("properties", string.Join(",", Properties));
rule.ValidationType = type;
yield return rule;
}
}
你在 class/viewmodel:
上这样使用它
public class Person
{
[OptionalRequired(new string[] { nameof(MobileNumber), nameof(LandLineNumber), nameof(FaxNumber) }, MinimumAmount = 2)]
public string MobileNumber { get; set; }
public string LandLineNumber { get; set; }
public string FaxNumber { get; set; }
}
使用此配置,您需要至少填写 2 个必填字段,否则将显示错误。
您可以将属性放在每个 属性 上,以便在所有这些上弹出错误消息。这就是你想要的
为了客户端验证,我在属性上添加了接口并设置了不同的参数,但 JavaScript 本身我没有。您需要查找它(例如 here )
此代码未经测试,但我认为它可以让您很好地了解事情是如何完成的。
我在 ASP.NET MVC 项目中使用 EF 数据注释,对于必填字段,我定义了如下所示的字段:
型号:
[Required(ErrorMessage = "Required!");
public string PhoneHome{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneWork{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneMobile { get; set; }
查看:
@Html.TextBoxFor(m => m.PhoneHome)
@Html.ValidationMessageFor(m => m.PhoneHome, null, new { @class = "field-validation-error" })
@Html.TextBoxFor(m => m.PhoneWork)
@Html.ValidationMessageFor(m => m.PhoneWork, null, new { @class = "field-validation-error" })
@Html.TextBoxFor(m => m.PhoneMobile )
@Html.ValidationMessageFor(m => m.PhoneMobile , null, new { @class = "field-validation-error" })
我只想将这些字段中的一个设为必填项(如果用户填写其中一个字段就可以,但是如果他没有填写其中任何一个我想显示一条错误消息并且不让他填写提交表格),但不知道执行此操作的最合适和更智能的方法?我是否应该在提交时使用 JavaScript 检查所有这些字段并显示必要的错误消息?或者我应该只使用数据注释来执行此操作吗?
public class MyModel : IValidatableObject
{
[Required(ErrorMessage = "Required!");
public string PhoneHome{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneWork{ get; set; }
[Required(ErrorMessage = "Required!");
public string PhoneMobile { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((PhoneHome+PhoneWork+PhoneMobile).Length < 1)
{
yield return new ValidationResult("You should set up any phone number!", new [] { "ConfirmForm" });
}
}
}
好的,我举了个例子。我创建了一个自定义验证属性,其中包含一些参数,例如需要哪些属性以及数量(最小值和最大值)。命名不是最好的,但它完成了工作(未测试)。如果您不关心客户端上的验证,则可以删除 ICIentValidatable(使用 jquery 验证,不显眼...)。
属性是这样制作的:
public class OptionalRequired : ValidationAttribute, IClientValidatable
{
/// <summary>
/// The name of the client validation rule
/// </summary>
private readonly string type = "optionalrequired";
/// <summary>
/// The (minimum) amount of properties that are required to be filled in. Use -1 when there is no minimum. Default 1.
/// </summary>
public int MinimumAmount { get; set; } = 1;
/// <summary>
/// The maximum amount of properties that need to be filled in. Use -1 when there is no maximum. Default -1.
/// </summary>
public int MaximumAmount { get; set; } = -1;
/// <summary>
/// The collection of property names
/// </summary>
public string[] Properties { get; set; }
public OptionalRequired(string[] properties)
{
Properties = properties;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int validPropertyValues = 0;
// Iterate the properties in the collection
foreach (var propertyName in Properties)
{
// Find the property
var property = validationContext.ObjectType.GetProperty(propertyName);
// When the property is not found throw an exception
if (property == null)
throw new ArgumentException($"Property {propertyName} not found.");
// Get the value of the property
var propertyValue = property.GetValue(validationContext.ObjectInstance);
// When the value is not null and not empty (very simple validation)
if (propertyValue != null && String.IsNullOrEmpty(propertyValue.ToString()))
validPropertyValues++;
}
// Check if the minimum allowed is exceeded
if (MinimumAmount != -1 && validPropertyValues < MinimumAmount)
return new ValidationResult($"You are required to fill in a minimum of {MinimumAmount} fields.");
// Check if the maximum allowed is exceeded
else if (MaximumAmount != -1 && validPropertyValues > MaximumAmount)
return new ValidationResult($"You can only fill in {MaximumAmount} of fields");
//
else
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = "Enter your error message here or manipulate it on the client side";
rule.ValidationParameters.Add("minimum", MinimumAmount);
rule.ValidationParameters.Add("maximum", MaximumAmount);
rule.ValidationParameters.Add("properties", string.Join(",", Properties));
rule.ValidationType = type;
yield return rule;
}
}
你在 class/viewmodel:
上这样使用它public class Person
{
[OptionalRequired(new string[] { nameof(MobileNumber), nameof(LandLineNumber), nameof(FaxNumber) }, MinimumAmount = 2)]
public string MobileNumber { get; set; }
public string LandLineNumber { get; set; }
public string FaxNumber { get; set; }
}
使用此配置,您需要至少填写 2 个必填字段,否则将显示错误。 您可以将属性放在每个 属性 上,以便在所有这些上弹出错误消息。这就是你想要的
为了客户端验证,我在属性上添加了接口并设置了不同的参数,但 JavaScript 本身我没有。您需要查找它(例如 here )
此代码未经测试,但我认为它可以让您很好地了解事情是如何完成的。