Description:
In this example
we explain that how perform Regular Expression using Data Annotation in Asp.Net
MVC.or Regular Expression using Data Annotation using MVC.the Data Annotation
can be applied to Model properties and used for the Regular Expression
Validation in MVC Razor view.
public class EmployeeModel
{
[Display(Name = "Username")]
[Required(ErrorMessage = "Username is required.")]
[RegularExpression("^[a-zA-Z0-9]*$", ErrorMessage = "Only Alphabets and Numbers allowed.")]
public string UserName { get;
set; }
}
Controller:
public class EmployeeController
: Controller
{
// GET: Home
public ActionResult Index()
{
return
View();
}
[HttpPost]
public ActionResult Index(EmployeeModel
employee)
{
return
View();
}
}
View:
@model
Alphanumeric_Validation_MVC.Models.PersonModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>RegularExpression
Data Annotation example: Perform validations using RegularExpression Data
Annotation in ASP.Net MVC</title>
<style type="text/css">
body
{
font-family:
Arial;
font-size:
10pt;
}
.error
{
color:
red;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index",
"Employee", FormMethod.Post))
{
<table>
<tr>
<td>@Html.LabelFor(m
=> m.UserName)</td>
<td>@Html.TextBoxFor(m
=> m.UserName)</td>
<td>@Html.ValidationMessageFor(m
=> m.UserName, "", new { @class = "error" })</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/></td>
<td></td>
</tr>
</table>
}
</body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
</html>
0 comments:
Post a Comment