Creating Your Own Validation Attribute In MVC And Web API 2.0

Data validation in an Appliction is one of the major task for the developer now-a-days. Data validation is the process of ensuring that the data entered by any users is correct and is a useful data. It uses routines, often called validation rules, validation constraints or check routines, which checks for correctness, meaningfulness and security of the data, which is input to the Web Application.These rules are mainly implemented in UI, business logic and in the database label.

If we check in any Web Application, we will found mainly the validations in UI label. As the user interface is the primary source, where the user can enter an invalid data to the Application, we mainly focus on UI validation.

In MVC, we have Dataanotations attributes, which will ensure data integrity while entering to the Application.

All DataAnnotation attributes are included in System.ComponentModel.DataAnnotations namespace. Various DataAnnotation attributes gives you a simple way to perform the validation on model data. These attributes are helpful for the common validation pattern like Required, Range, StringLength etc.

It can perform the validation on both client and Server side.

The main Data Validation attributes are given below.

  1. Required - It ensures that the value must be provided to the model property.
  2. Range- The data should be in specific range like age should not be between 1 to 18.
  3. StringLength- You can specify the minimum and maximum length of property value.
  4. Compair- It is used to compare one property value with another.
  5. Regular Expression- The value should match regular expression e.g. E-mail, phone, URL etc.

However sometimes when these validators fails to validate certain business rules; we require custom validation for custom business rules.

Hence, we will see how can we implement these in MVC Application.

Requirement

Here, I have a model, as shown below.

public class RegisterViewModel  
{  
    [Required]  
    [EmailAddress]  
    [Display(Name = "Email")]  
    public string Email { get; set; }  

    [Required]  
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
    [DataType(DataType.Password)]  
    [Display(Name = "Password")]  
    public string Password { get; set; }  
    [Required(ErrorMessage ="First Name is Required")]  
    public string FirstName { get; set; }  
    [Required(ErrorMessage = "Last Name is Required")]  
    public string LastName { get; set; }
    public string Country { get; set; }
}

Thus, I have a country property. Here, I want to implement the validation.The  Application should accept only these 3 countries like (India,Pakistan,Nepal).

As of now, I don't find any validation attribute, which will fulfill my requirement, so I will go for Custom Validation.

Before implementing Custom Validation, we shold know about a class i.e. ValidationAttribute.

ValidationAttribute class is an abstract class, which contains IsValid virtual method. IsValid method takes the value and ValidationContext object as the input parameters.

Value represents the value of the model property for which this Custom Validation applies. ValidationContext describes the context in which validation check is performed.

Thus, for this custom validation, add a new class called checkCountry as shown below and derive it from ValidationAttribute class.

public class CustomValidation
{  
    public sealed class checkCountry : ValidationAttribute  
    {  
        public String AllowCountry { get; set; }  

        protected override ValidationResult IsValid(object country, ValidationContext validationContext)  
        {  
            string[] myarr = AllowCountry.ToString().Split(',');  
            if(myarr.Contains(country))  
            {  
                return ValidationResult.Success;  
            }  
            else  
            {  
                return new ValidationResult("Please choose a valid country eg.(India,Pakistan,Nepal");  
            }  
        }
    }
}

Now, use the namespace given below and modify the model, as shown below.

using System.ComponentModel.DataAnnotations;  
using static customValidation.CustomValidation;

Now, you have the attributes checkcountry in the model property, as shown.

[checkCountry(AllowCountry ="India,Pakistan,Nepal",ErrorMessage = ("Please choose a valid country eg.(India,Pakistan,Nepal")]  
public string Country { get; set; }  

Now, add the details given below and click Register in View.

Here, the source code for View is given below.

@model customValidation.Models.RegisterViewModel  
@{  
//ViewBag.Title = "Register";  
}  
  
<h2>@ViewBag.Title.</h2>  
  
  
  
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))  
{  
    @Html.AntiForgeryToken()  
    <h4>Create a new account.</h4>  
    <hr />  
    @*@Html.ValidationSummary("", new { @class = "text-danger" })*@  
    <div >  
        <div class="form-group" >  
            @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })  
            <div class="col-md-10">  
                @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })  
               @Html.ValidationMessageFor(model => model.Email,null, new { @class = "text-danger" })   
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })  
            <div class="col-md-10">  
                @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
                @Html.ValidationMessageFor(model => model.Password, null, new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" })  
            <div class="col-md-10">  
                @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" })  
                @Html.ValidationMessageFor(model => model.FirstName, null, new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })  
            <div class="col-md-10">  
                @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" })  
                @Html.ValidationMessageFor(model => model.LastName, null, new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            @Html.LabelFor(m => m.Country, new { @class = "col-md-2 control-label" })  
            <div class="col-md-10">  
                @Html.TextBoxFor(m => m.Country, new { @class = "form-control" })  
                @Html.ValidationMessageFor(model => model.Country, null, new { @class = "text-danger" })  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" class="btn btn-default" value="Register" />  
            </div>  
        </div>  
    </div>  
}  
  
@section Scripts {  
    @Scripts.Render("~/bundles/jqueryval")  
}

Now, just put a breakpoint and check the execution.

Now, it will check; if the entered country is present in allowcountry by splitting the string, if not; then it will return an error message.

Here, Controller code is given below.

// POST: /Account/Register
[HttpPost]  
[AllowAnonymous]  
[ValidateAntiForgeryToken]  
public async Task<ActionResult> Register(RegisterViewModel model)  
{  
    if (ModelState.IsValid)  
    {  
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };  
        var result = await UserManager.CreateAsync(user, model.Password);  
        if (result.Succeeded)  
        {  
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);  
              


            return RedirectToAction("Index", "Home");  
        }  
        AddErrors(result);  
    }  

    // If we got this far, something failed, redisplay form  
    return View(model);  
}

Here, the output is produced.

In this way, we can create our own validation attributes and can use in the project.

Now, check this functionality in Web API 2.0.

Create a MVC WebAPI project.

Add the model given below.

public class Register  
{  
    [Required]  
    [EmailAddress]  
    [Display(Name = "Email")]  
    public string Email { get; set; }  
    public string FirstName { get; set; }  
    [Required(ErrorMessage = "Last Name is Required")]  
    public string LastName { get; set; }  

    public string Country { get; set; }  
}

Now, add a class to create your own validation, as shown below.

public sealed class checkCountry : ValidationAttribute  
{  
    public String AllowCountry { get; set; }  

    protected override ValidationResult IsValid(object country, ValidationContext validationContext)  
    {  
        string[] myarr = AllowCountry.ToString().Split(',');  
        if (myarr.Contains(country))  
        {  
            return ValidationResult.Success;  
        }  
        else  
        {  
            return new ValidationResult("Please choose a valid country eg.(India,Pakistan,Nepal)");  
        }  
    }  

} 

Now, add the attribute in the model.

public class Register  
{  
    [Required]  
    [EmailAddress]  
    [Display(Name = "Email")]  
    public string Email { get; set; }  
    public string FirstName { get; set; }  
    [Required(ErrorMessage = "Last Name is Required")]  
    public string LastName { get; set; }  

    [checkCountry(AllowCountry = "India,Pakistan,Nepal", ErrorMessage = "please enter a valid country eg( India,SriLanka,Nepal.)")]  
    public string Country { get; set; }  
}

Now, Register Controller is shown.

The actual code for Controller action method is given.

[Route("Register")]  
public async Task<HttpResponseMessage> RegisterUser(Register obj)  
{  
    Dictionary<string, object> dict = new Dictionary<string, object>();  

    if (!ModelState.IsValid)  
    {  
        string errordetails = "";  
        var errors = new List<string>();  
        foreach (var state in ModelState)  
        {  
            foreach (var error in state.Value.Errors)  
            {  
                string p = error.ErrorMessage;  
                errordetails = errordetails + error.ErrorMessage;  

            }  
        }  

        dict.Add("error", errordetails);  
        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);  

    }  
    else  
    {  
        dict.Add("Success", "Register successfully");  
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK,dict);  
        return response;  
    }  

}

Now, check the Register method, using PostMan client.

Lets put an invalid country and test first.

Now, put the valid data and test the result.

Thus, in this way, we can create our validation attribute and use it in both MVC and WebAPI. 


Similar Articles