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 create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article