Friday, March 6, 2015

How to add Multiple Regular Expression Validation attribute into one Property in ASP.Net MVC?

Create another new attribute and inherit from RegularExpressionAttribute

    public class RegularExpressionAttribute : ValidationAttribute
        private string _pattern;
        public RegularExpressionAttribute(string pattern)
            _pattern = pattern;
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            if (value == null) return null;
            if (!System.Text.RegularExpressions.Regex.IsMatch(value.ToString(), _pattern))
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            return null;

    public class RegularExpression2ndAttribute : RegularExpressionAttribute {}

So in view model:
        [ValidURL(ErrorMessage = "Invalid URL")]
        [RegularExpression(@"^.*\.(jpg|JPG|gif|GIF|jpeg)$", ErrorMessage = "Not a image URL")]
        public string LogoUrl { get; set; }

No comments:

Post a Comment