How can I set the string validation for a fixed-length string using data annotation ?
I want to have a property on my model with the exact 10 string-length.
I'm counting the seconds for help.
DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.
In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
The StringLength Attribute Specifies both the Min and Max length of characters that we can use in a field.
1) [StringLength(10, MinimumLength = 10)]
2) [RegularExpression(@"(.{10})")]
Try
[StringLength(10, MinimumLength = 10, ErrorMessage = "This field must be 10 characters")]
public string myString {get;set;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With