简体   繁体   English

在MVC中使用模型数据注释来确保一个字符串仅包含一个单词?

[英]Using model data annotation in MVC to ensure a string contains just one word?

Is there some way using data annotations that I can check the value of a property in my model is just a single word? 有什么方法可以使用数据注释来检查模型中的属性值只是一个单词? I know how to check it's maximum length but I've no idea how to do the single word check. 我知道如何检查最大长度,但不知道如何检查单个单词。

Yes you can. 是的你可以。 You can use a regex in your model for the validation. 您可以在模型中使用正则表达式进行验证。

[RegularExpression(@"\b*[a-zA-Z0-9_]\b", ErrorMessage = "Enter A Single Word Please")]
string FirstName {get; set;}

A single word of only letters and numbers with a minimum length of 4 and maximum length of 50 characters and a message showing the minimum: 一个仅包含字母和数字的单词,最小长度为4,最大长度为50个字符,并显示一条消息,提示最小:

    [RegularExpression(@"[a-zA-Z\d]{4,}", ErrorMessage = "Invalid.")]
    [StringLength(50, MinimumLength = 4, ErrorMessage = "Must be at least {2} characters long.")]

A single word of only letters with a minimum length of 4 and maximum length of 30 characters and a message showing the range: 一个只有几个字母的单词,最小长度为4,最大长度为30个字符,并显示一条消息,显示范围:

    [RegularExpression(@"[a-zA-Z]{4,}", ErrorMessage = "Invalid.")]
    [StringLength(30, ErrorMessage = "Must be between {2} and {1} characters long.", MinimumLength = 4)]

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

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