Thursday, October 11, 2012

Form Validation in Asp.net MVC2

Now we learn how to do validation in MVC2 ! Yes that's not exactly the way we used to do in asp.net , (i am assuming you are familiar with Model View Controller), in MVC2 we can specify each field validation in model level, So let's  take a look at how the model will look like!


 public class ClientModel : BaseModel
    {
        public long ContactId { get; set; }

        [Required(ErrorMessage = "Organisation name required.")]
        [DisplayName("Organisation Name")]
        public string OrgName { get; set; }

        [DisplayName("Address")]
        public string Address { get; set; }

        [Required(ErrorMessage = "Organisation type required.")]
        [DisplayName("Type")]
        public string OrgType { get; set; }

        [DataType(DataType.EmailAddress)]
        [DisplayName("Email")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Enter contact person name.")]
        [DisplayName("Concern Person")]
        public string ConcernPerson { get; set; }

[ValidateClientDOBAttribute]
        public DateTime? ClientDOB { get; set; }

        [DataType(DataType.Date)]
        public DateTime? ClientAnniversery { get; set; }
    }

the below is an example of custom validation class that we have used for some field validation above (ClientDOB), we can write custom validation for any field as per our business need

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]

    public sealed class ValidateClientDOBAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "Provide valid date format- dd/MM/yyyy";
        private readonly string _pastDate = "past date not allowed";

        public ValidateClientDOBAttribute()
            : base(_defaultErrorMessage)
        {
        }

        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                name, _pastDate);
        }

        public override bool IsValid(object value)
        {
            bool Valid = false;
            DateTime? valueAsDate = value as DateTime?;
            // if null then allowed.
            if (valueAsDate == null)
                Valid = true;
            return Valid;
        }
    }

Now we are ready to see how to consume this validation in aspx page!

the first line you need to specify before you start the form tag is  < % Html.EnableClientValidation(); %> this will indicate that the model validation message to be displayed on your form

now we start form tag, you can use normal form or ajax form, this will work with both types.

  < % using (Ajax.BeginForm("AddClient", new AjaxOptions
               {
                   UpdateTargetId = "dvAddClient",
                   InsertionMode = InsertionMode.Replace,
                   OnBegin = "ajaxValidate",
                   OnSuccess = "getGbPostSuccess",
                   OnFailure = "showFaliure",
                   Confirm = "You sure?"
               }))
% >

now you can display the validation message both way either in form of validation summary or inline, or both. in case you want to display validation summary at the top of the form put the line below.
  < %: Html.ValidationSummary(false, "Client addintion was unsuccessful. Please correct the errors and try again.")% >

Or if you want to display inline validation message, please write this way:
 <%: Html.ValidationMessageFor(m => m.OrgName)%>

i hope you find this helpful.



No comments: