Showing posts with label Required. Show all posts
Showing posts with label Required. Show all posts

Friday, November 6, 2015

ASP.NET MVC - Customizing RequiredAttribute to display required field validation errors in a different format than the default one

Consider a scenario where you want all Required validators of your MVC application to display error messages in a different format than the default one.
As of ASP.NET MVC 5, the default error message format for required field validator is "The <<field display name>> field is required." For example, "The User name field is required." or "The Password field is required."

But instead, you want them to display in a different format, like - "Please enter value in <<field display name>>." Examples - "Please enter value in User name input box", or "Please enter value in Password input box".

One option is to set "ErrorMessage" property of Required data annotation for each and every fields where this validator is used. However, this can solve the purpose, but it will be tedious and importantly, maintenance nightmare to do so.

Perform following steps to customize default error message of Required validators, and apply them across the application.

Step - 1 Create following custom attribute (for instance, "CustomizedRequiredValidatorAdapter") inheriting from RequiredAttributeAdapter:

    public class CustomizedRequiredValidatorAdapter: RequiredAttributeAdapter
    {
        public CustomizedRequiredValidatorAdapter(ModelMetadata metadata,
                                    ControllerContext context,
                                    RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
            attribute.ErrorMessage = "Please enter value in {0}.";
        }
    }

This requires "System.Web.Mvc", and "System.ComponentModel.DataAnnotations" namespaces

Step - 2 Replace default RequiredAttribute validator by the one created in Step - 1

Add following in the Application_Start event of Global.asax.cs file:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
                typeof(RequiredAttribute),
                typeof(CustomizedRequiredValidatorAdapter));

That's it! This is all you need to do. Now try running your MVC application and see the error messages on required validation failures and you should see the customized messages.

Further, if you have Globalization implemented, you can set attribute.ErrorMessageResourceType, and attribute.ErrorMessageResourceName in the custom attribute (step - 1) to get the string Error message string from resources file.

Saturday, April 21, 2012

Simple client-side Validations using ASP.NET MVC

This article aims to demonstrate how we can apply simple validations at view (page) level in ASP.NET MVC.

Say, you have a "Person" model, that you pass in the view to and fro controller action.

A Person model is having many fields, one of them is "PersonName" (Label: Person Name) and you want to make it required when user inputs data in corresponding view of this model.

In order to achieve this, first decorate PersonName field in Person model with "Required" attribute.
"Required" attribute is a part of System.ComponentModel.DataAnnotations namespace. So this must be imported in your model (using System.ComponentModel.DataAnnotations)

System.ComponentModel.DataAnnotations contain various attributes that can be applied on a model field. Along with that it has all necessary validators (like, Required, Range, MaxLength, MinLength, Regular Expression, Custom validator, etc).

For our case, we should write - 

[Required(ErrorMessage="Please Enter Person Name!")]
[Display(Name="Person Name")]
public string PersonName { get; set; }

This will automatically handle required validation for Person Name field input.
Now, in the view (.aspx, or .cshtml), we need to put ValidationSummary in order to display error message in case validation fails.
@Html.ValidationSummary(false, "Please correct following errors and try again!")

The last thing is to add a condition in HttpPost method to relaunch the view with latest inputs and error messages, in case if validation(s) fail.

[HttpPost]
        public ActionResult PersonEdit(Person person)
        {
            if (ModelState.IsValid == false)
            {
                return View("PersonEdit",  person);
            }
            else
            {
             //Write code to define actions on success
            }            
        }

Now, when the view is launched with person model, it will have same inputs as well as validation errors, so that they will get displayed in ValidationSummary control in view to let users know about the errors.

NOTE: Also, remember to put @Html.ValidationSummary control before @Html.BeginForm block, otherwise it will always show you validation messages even before HttpPost.