Saturday, 27 February 2021

MVC - Custom Validation - Get display name of first, second and third property in both client and server validation

Watch this example on YouTube

 

 

 

1. Validation Function

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Reflection;

namespace WebApplication10.Models
{
    public class ValidateCheckBoxAttribute: ValidationAttribute, IClientValidatable
    {
        private readonly string[] _fields;
        private const string DefaultErrorMessage = "{0} is mandatory";
        public string firstPropertyName { get; set; }
        public ValidateCheckBoxAttribute(string[] fields)
        {
            _fields = fields;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo propertyFirst = validationContext.ObjectType.GetProperty(_fields[0]);
            PropertyInfo propertySecond = validationContext.ObjectType.GetProperty(_fields[1]);
            PropertyInfo property3 = validationContext.ObjectType.GetProperty(_fields[2]);

            var valueFirst = propertyFirst.GetValue(validationContext.ObjectInstance, null);
            var valueSecond = propertySecond.GetValue(validationContext.ObjectInstance, null);
            var value3 = property3.GetValue(validationContext.ObjectInstance, null);

            var dispFirst = ModelMetadataProviders.Current.GetMetadataForProperty(null, validationContext.ObjectType, _fields[0]);
            var dispSecond = ModelMetadataProviders.Current.GetMetadataForProperty(null, validationContext.ObjectType, _fields[1]);
            var disp3 = ModelMetadataProviders.Current.GetMetadataForProperty(null, validationContext.ObjectType, _fields[2]);
            var firstName = dispFirst.GetDisplayName();
            var secondName = dispSecond.GetDisplayName();
            var th = disp3.GetDisplayName();
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            Type type = Type.GetType(metadata.ContainerType.FullName);
            var model = Activator.CreateInstance(type);
            var provider = new DataAnnotationsModelMetadataProvider();
            var firstDisplayName = provider.GetMetadataForProperty(() => model, type, _fields[0]);
            var secondDisplayName = provider.GetMetadataForProperty(() => model, type, _fields[1]);
            var thirdDisplayName = provider.GetMetadataForProperty(() => model, type, _fields[2]);
            var one = firstDisplayName.DisplayName;
            var second = secondDisplayName.DisplayName;
            var third = thirdDisplayName.DisplayName;
            var rule = new ModelClientValidationRule
            {
                ValidationType = "validatecheckbox",
                ErrorMessage =  " is mandatory"
            };
            rule.ValidationParameters.Add("fields", string.Join(",", _fields));
            yield return rule;
        }
    }
}


2.  Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication10.Models
{
    public class Customer
    {
        [ValidateCheckBox(new string[] { "IsActive", "FirstName", "LastName"})]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Display(Name="Is Active")]
        public bool IsActive { get; set; }

        [Display(Name = "Last Name etc....")]
        public string LastName { get; set; }
    }
}

No comments:

Post a Comment