开发者

MVC - multiple data annotations on the same property

I am trying to use the data annotations in MVC 3. Thus, I want to have multiple annotations on a single property. First, I want to check for the length of the username entered by the user, and show the corresponding error开发者_如何学运维 message if the name is not in the range of 3 to 13 characters.

When the first check has been made, I want to check for the second annotation with the Regex. Meaning, I will check for the regex for strings between 3 and 13, and for anything else, I will display the first error message.

[Required(ErrorMessage = "Enter a username")]
[StringLength(13, MinimumLength = 3, ErrorMessage="Username must be between 3 and 13")]
[RegularExpression("^[a-z0-9.]{3,15}$", ErrorMessage = "Only the letters (a-z), numbers (0-9) and dots (.), are allowed")]
[DataType(DataType.Text)]
[Display(Name = "Username")]
public string UserName { get; set; }

Now, when i enter a single character in the username field, the correct message is shown. When entering a second character, the error message from the reqex is displayed? Why? And can this be done in a different way?

Thanks,

Regards.


You can create your own validator that derives from ValidationAttribute. You can then implement any logic you like.

See the third post in this thread


Perhaps you mean you want to check attributes in a particular order? I'm not to sure whether an expected ordering is possible. You can always write a custom validation instead (using a cusomt attribute to combine the checks), that will give you full control over the exact message.

By the way, I assume you meant 'regex' instead of 'reqex' in reference to the RegularExpression? Then it would make a lot of sense for that message to appear < 3 characters because it is the minimum required by the regex. You could do away with the StringLength attribute, because it is redundant with the regex.


The simplest answer is, perhaps, the best. Simply remove the length requirement from the regular expression and it won't flag based on length. Allow the StringLength annotation to do that job.

[Required(ErrorMessage = "Enter a username")]
[StringLength(13, MinimumLength = 3, ErrorMessage="Username must be between 3 and 13")]
[RegularExpression("^[a-z0-9.]$", ErrorMessage = "Only the letters (a-z), numbers (0-9) and dots (.), are allowed")]
[DataType(DataType.Text)]
[Display(Name = "Username")]
public string UserName { get; set; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜