The RangeValidation is used to check that the user enters an input value that falls between two values. It is possible to check ranges within numbers, dates, and characters.
Introduction
In this article we will see how to use Range Validation in ASP.NET Application that uses web API..This article is for
obsolete beginners.
- Step 1 Create a New Project Open visual studio 2013 -> click on File -> New Project -> Create new ASP.NET MVC Web Application -> Name it as SampleRangeValidation,
Select WEB API Template and click OK
- Step 2 Now find the Models folder in solution created and right click on it and add a class named Testclient as shown below
Using the code
Here we have used System.ComponentModel.DataAnnotations namespace
Here we have given user to enter only in range between 1 to 100
using System.ComponentModel.DataAnnotations;
namespace SampleRangeValidation.Models
{
public class Testclient
{
[Required(ErrorMessage = "Pleasee enter Total Students")]
[Range(0, 100, ErrorMessage = "Enter number between 0 to 100")]
public int TotalStudents { get; set; }
}
}
- Step 3 Now Lets modify the Homecontroller which we can find in Controllers folder..add the following implementation
using SampleRangeValidation.Models;
using System.Web.Mvc;
namespace SampleRangeValidation.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
[HttpPost]
public ActionResult Index(Testclient objclient)
{
if (ModelState.IsValid)
{
ViewBag.message = "Now The number is in Range";
}
return View();
}
}
}
- Step 4 Now Lets modify the View which we find under Views-->Home-->Index.cshtml
@model SampleRangeValidation.Models.Testclient
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home"))
{
<fieldset>
<h1>Add Total students</h1>
@Html.TextBoxFor(m => m.TotalStudents)
@Html.ValidationMessageFor(m => m.TotalStudents)
<p>
<input type="submit" value="Submit" />
</p>
@ViewBag.message
</fieldset>
}
Debug the Application by pressing F5 we should find the following output
After user input we can see the following validation message
Conclusion
In this article we have seen how to use Range validation.Hope you have enjoyed the article