How to use StringLength to limit the length of a string property in a model.
How to use StringLength to limit the length of a string property in a model.
447
20-Oct-2023
Updated on 22-Oct-2023
Aryan Kumar
22-Oct-2023You can use the StringLength data annotation in .NET Core to limit the length of a string property in a model. The StringLength attribute allows you to specify both the minimum and maximum length for a string property. Here's how to use it:
Import the Required Namespace:
Ensure that you've imported the System.ComponentModel.DataAnnotations namespace, which contains the StringLength attribute.
Apply the StringLength Attribute:
Apply the StringLength attribute to the string property in your model class. You can set the MinimumLength and MaximumLength properties to define the acceptable range for the string's length.
In this example, the Name property is decorated with the StringLength attribute, which specifies that the minimum length is 3 characters and the maximum length is 50 characters. The ErrorMessage property is also set to provide a custom error message if the validation fails.
Display Validation Errors in Views:
In your views, use the ValidationMessageFor HTML helper to display validation errors for the property.
This code will display the custom error message defined in the StringLength attribute when the string length is outside the specified range.
Server-Side Validation:
In your controller action methods, you can check the ModelState.IsValid property to determine if the validation has passed. If ModelState.IsValid is false, you can handle validation errors as needed.
By using the StringLength data annotation, you can ensure that a string property in your model complies with the specified length constraints, providing meaningful validation error messages and enhancing the user experience.