Part 81 - Range attribute in asp.net mvc

Leave a Comment
RangeAttribute checks if the value of a data field is within a specified range of values. We will be working with the example, that we started in Part 80.

When you navigate to /Home/Edit/1, notice that we don't have validation on Age field. If you enter 5000 as the age and click Save, the date gets saved. Obviously an employee having 5000 years as the age is not practical. So, let's validate Age field, and enforce users to enter a value between 1 and 100. To achieve this RangeAttribute can be used.

Make the following change to the Employee class in Employee.cs file in Models folder. Notice that, we are using RangeAttribute, and have set minimum and maximum as 1 and 100 respectively.
public class EmployeeMetaData
    [StringLength(10, MinimumLength = 5)]
    public string Name { getset; }

    [Range(1, 100)]
    public int Age { getset; }

At this point, we should not be able to enter any values outside the range of 1 and 100 for Age field.

Range attribute can also be used to validate DateTime fields. Let's now discuss using Range attribute with DateTime fields.

At the moment our Employee class does not have any DateTime field. Let's add HireDate column to table tblEmployee. Use the sql script below to alter the table.
Alter table tblEmployee
Add HireDate Date

SQL script to update the existing employee records:
Update tblEmployee Set HireDate='2009-08-20' where ID=1
Update tblEmployee Set HireDate='2008-07-13' where ID=2
Update tblEmployee Set HireDate='2005-11-11' where ID=3
Update tblEmployee Set HireDate='2007-10-23' where ID=4

Update the ADO.NET data model.
1. In the Solution Explorer, double click on SampleDataModel.edmx file in Models folder.
2. Right click on "Employee" model and select "Update Model from database" option
3. Click on "Refresh" tab on "Update Wizard"
4. Expand "Tables" and select "tblEmployee" table and click "Finish.
5. These steps should add HireDate property to the autogenerated Employee entity class

Build the solution to compile Employee entity class.

Copy and paste the following 2 DIV tags in Edit.cshtml view, just above the "Save" button.
<div class="editor-label">
    @Html.LabelFor(model => model.HireDate)
<div class="editor-field">
    @Html.EditorFor(model => model.HireDate)
    @Html.ValidationMessageFor(model => model.HireDate)

Make the following change to the Employee class in Employee.cs file in Models folder. Notice that, we are passing DateTime as the type and specifying the minimum and maximum values for HireDate. We are also using DisplayFormat attribute, so that only date part of DateTime is displayed in the Edit view.
public class Emplo


Post a Comment

Note: only a member of this blog may post a comment.