31 March 2013

MVC- Custom Data Annotations validation server and client side







           public class TestModel2
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Name is Required")]
                public string Name { get; set; }
                [Required(ErrorMessage = "Email is Required")]
                [RegularExpression(@"^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$",
                     ErrorMessage = "Please enter valid email")]
                public string Email { get; set; }
                [StringLength(300)]
                public string Description { get; set; }
                [Compare("Email", ErrorMessage = 
                    "User name should be email id")]
                public string Username { get; set; }
                public DateTime PlanStratDate { get; set; }
                public DateTime PlanEndDate { get; set; }
                public string ExternalId { get; set; }
            }

           






       
        public class TestModel2
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Name is Required")]
                public string Name { get; set; }
                [Required(ErrorMessage = "Email is Required")]
                [RegularExpression(@"^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$", 
                ErrorMessage = "Please enter valid email")]
                public string Email { get; set; }
                [StringLength(300)]
                public string Description { get; set; }
                [Compare("Email", ErrorMessage =
                "User name should be email id")]
                public string Username { get; set; }
                public DateTime PlanStratDate { get; set; }
                [GratherThen("PlanStratDate")]
                public DateTime PlanEndDate { get; set; }
                [ExternalIdPattern]
                public string ExternalId { get; set; }
            }

        






       public class ExternalIdPatternAttribute : ValidationAttribute , IClientValidatable
        {
            public ExternalIdPatternAttribute() : 
            base("External id should be match with system pattern") { }

            public override bool IsValid(object value)
            {
                const string matchingPattern = "code4help";
                return Convert.ToString(value).Contains(matchingPattern);
            }

            public IEnumerable[ModelClientValidationRule] GetClientValidationRules
            (ModelMetadata metadata, ControllerContext context)
                {
                   var errorMessage = ErrorMessageString;
                    var extidrule = new ModelClientValidationRule();
                    extidrule.ErrorMessage = errorMessage;
                    extidrule.ValidationType = "externalidpattern";
                    //extidrule.ValidationParameters.Add("otherpropertyname",
                         otherPropertyName);

                    yield return extidrule;
                }
         }


                
                


        public class GratherThenAttribute : ValidationAttribute , IClientValidatable
            {
                public string OtherProperty { get; set; }

                public GratherThenAttribute(string oprop)
                    : base("{0} should be grather then {1}")
                {
                    this.OtherProperty = oprop;
                }

                protected override ValidationResult IsValid(object value,
                 ValidationContext validationContext)
                {
                    var validationResult = ValidationResult.Success;
                    var otherPropertyval = 
                    validationContext.ObjectType.GetProperty(this.OtherProperty);
                    if (otherPropertyval.PropertyType == new DateTime().GetType())
                    {
                        var edate = (DateTime)value;
                        var sdate = 
                        (DateTime)otherPropertyval.GetValue(validationContext.ObjectInstance,
                         null);

                        if (edate.CompareTo(sdate) < 1)
                            validationResult = new ValidationResult(ErrorMessageString);
                    }
                    else
                        validationResult =
                            new ValidationResult(
                                "An error occurred while validating the property.
                                 OtherProperty is not of type DateTime");
                    return validationResult;
                }

                public IEnumerable[ModelClientValidationRule] 
                    GetClientValidationRules(ModelMetadata metadata, 
                    ControllerContext context)
                        {
                            var errorMessage = ErrorMessageString;

                            var extidrule = new ModelClientValidationRule();
                            extidrule.ErrorMessage = errorMessage;
                            extidrule.ValidationType = "gratherthen";
                            extidrule.ValidationParameters.Add("otherproperty", OtherProperty);

                            yield return extidrule;
                        }
                    }

            






            $.validator.addMethod("externalidpattern", function (value, element, params) {
            return Date.parse(value) > Date.parse($(params).val());
            });
            $.validator.unobtrusive.adapters.add("externalidpattern", [], function (options) {
                options.rules["externalidpattern"] = "#" + options.params.otherpropertyname;
                options.messages["externalidpattern"] = options.message;
            });

            $.validator.addMethod("gratherthen", function (value, element, params) {
                return Date.parse(value) > Date.parse($(params).val());
            });
            $.validator.unobtrusive.adapters.add("gratherthen", ["otherproperty"], function (options) {
                options.rules["gratherthen"] = "#" + options.params.otherpropertyname;
                options.messages["gratherthen"] = options.message;
            });

            




No comments:

Post a Comment