Sunday, June 9, 2013

Custom Validation in ASP.NET MVC

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.

public class LogIN
        [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.


public ActionResult SubPost(LogIN lg)      
   if (ModelState.IsValid)          
       //Code if Model Valid          
  return View();        


  @using (Html.BeginForm()) {
            <div class="editor-label">
                @Html.LabelFor(model => model.Email)
            <div class="editor-field">
                @Html.EditorFor(model => model.Email)
                @Html.ValidationMessageFor(model => model.Email)
                <input type="submit" value="Create" />

No comments:
Write comments
Recommended Posts × +