简体   繁体   English

如何验证字符串的模型可以在10到30个字符之间,也可以为空-C#ASP.NET

[英]How to validate model of so string can be between 10 and 30 characters, or empty - C# ASP.NET

I'm trying to validate incoming JSON using the Required attribute on a model that contains phone numbers. 我正在尝试在包含电话号码的模型上使用Required属性来验证传入的JSON。 There are two phone number properties, a Primary (required) and Alternate. 有两个电话号码属性,“主要”(必填)和“备用”。 For the Alternate, I want an empty string to be valid, but strings between 1 and 9 characters and more than 30 characters to be invalid. 对于Alternate,我希望一个空字符串有效,但1到9个字符之间以及30个以上字符之间的字符串无效。 This does not work: 这不起作用:

public class PhoneCreateModel
{
    [Required(AllowEmptyStrings = false,
        ErrorMessageResourceName = "PrimaryPhoneNumberRequired",
        ErrorMessageResourceType = typeof(DataAnnotationMessage))]
    [StringLength(30, MinimumLength = 10,
        ErrorMessageResourceName = "PrimaryPhoneNumberFormat",
        ErrorMessageResourceType = typeof(DataAnnotationMessage))]
    public string Primary { get; set; }

    [StringLength(30, MinimumLength = 10,
        ErrorMessageResourceName = "AlternatePhoneNumberFormat",
        ErrorMessageResourceType = typeof(DataAnnotationMessage))]
    public string Alternate { get; set; }
}

... because it doesn't allow Alternate to be an empty string. ...,因为它不允许Alternate为空字符串。 How can I allow it to be an empty string OR between 10-30 characters? 如何允许它为空字符串或10到30个字符?

You can implement your own validation attribute. 您可以实现自己的验证属性。 It is easier than it seems, just make a class which extends ValidationAttribute , and implement your logic in IsValid function. 它比看起来容易,只需创建一个扩展ValidationAttribute的类,然后在IsValid函数中实现您的逻辑即可。

Here's an example: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/custom-data-annotations-or-custom-validation-attributes-in-m/ 这是一个示例: http : //www.c-sharpcorner.com/UploadFile/abhikumarvatsa/custom-data-annotations-or-custom-validation-attributes-in-m/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM