In this example, I will show you to apply maxLength attribute to a string property in a class. You can set the maximum value for the property using data annotation validation property maxLength attribute.
For example, I created column field Name with nvarchar(20) for the table UserLogin. Then, using entity framework I generated the class and applied validation for the name property in userlogin class. If the user enters the value more than the 20 characters, it will show a validation message. You can also customize the error message like below example.
Entity framework generated class:
using System.ComponentModel.DataAnnotations;
public partial class UserLogin
{
public int UserLoginID { get; set; }
[MaxLength(20, ErrorMessage = "maximum {1} characters allowed")
public string Name { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
public string Address { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
Razor View:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>UserLogin</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name, new { Class = "form-control" })
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DOB, new{id = "DOB", Class = "form-control"})
@Html.ValidationMessageFor(model => model.DOB)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Address, new { Class = "form-control" })
@Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.Password, new { Class = "form-control box", type = "Password" })
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email, new { Class = "form-control" })
@Html.ValidationMessageFor(model => model.Email)
</div>
</fieldset>
<button type="submit" class="btn btn-success">Create</button>
}
Asp.net data validation:
Post your comments / questions
Recent Article
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
- OSError: cannot write mode RGBA as JPEG- Python
- expected str, bytes or os.PathLike object, not JpegImageFile - Python
Related Article