如何在 c# asp.net 模型中自定义消息双"Field must a number"



======型号.cs======

[MyCustomDoubleMessage(ErrorMessage = "Road length must be a number.")]
public double road_lenth {get; set;}

如果没有我的自定义说明,默认错误消息=>"道路长度必须是一个数字。">

我可以像上面那样更改默认消息吗?谢谢

使用以下属性

[Display(Name = "Road length")]
[MyCustomDoubleMessage(ErrorMessage = "Road length must be a number.")]
public double road_lenth {get; set;}

如下所示编写新的自定义属性将逻辑更改为double而不是not null

public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
private String displayName;
public RequiredAttribute()
{
this.ErrorMessage = "{0} is required";
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var attributes = validationContext.ObjectType.GetProperty(validationContext.MemberName).GetCustomAttributes(typeof(DisplayNameAttribute), true);
if (attributes != null)
this.displayName = (attributes[0] as DisplayNameAttribute).DisplayName;
else
this.displayName = validationContext.DisplayName;
return base.IsValid(value, validationContext);
}
public override string FormatErrorMessage(string name)
{
return string.Format(this.ErrorMessageString, displayName);
} 
}

并且模型必须像下面那样

[DisplayName("Road length")]
[Required]
public string road_lenth { get; set; }

相关内容

  • 没有找到相关文章

最新更新