Using Data Annotations ASP.NET MVC enables server side validations by default. There are some built in validations in Data Annotations like Required, MaxLength etc..
But what if you want to do some validation against the database. Something like check the Email address exists in your database and notify the user that the email already exists.
Model:
public class LogIN
{
[Required]
[CheckEmail(ErrorMessage="Email Aready Exists")]
public string Email { get; set; }
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = false, Inherited = true)]
public class CheckEmail : ValidationAttribute
{
public string UserEmail { get; set; }
public override bool IsValid(object value)
{
if (value != null)
{
//Here i check the database values against the Email entered by the email. I've used Entity Frmework and LINQ. You may use you'r own methods.
DataClasses1DataContext dc = new DataClasses1DataContext();
bool email = (from tbuser in dc.tblClients
where tbuser.Name == value.ToString()
select tbuser).Any();
if (email)
{
return false;
}
}
return true;
}
}
When you call ModelState.IsValid in you'r controller above validation will be fired.
Controller:
[HttpPost]
public ActionResult SubPost(LogIN lg)
{
if (ModelState.IsValid)
{
//Code if Model Valid
}
return View();
}
View:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>LogIN</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Sunday, June 9, 2013
Custom Validation in ASP.NET MVC
Subscribe to:
Post Comments (Atom)
No comments:
Write comments