i18N localized version of System.ComponentModel.DataAnnotations.RegularExpressionAttribute class.

Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.

Inheritance: System.ComponentModel.DataAnnotations.RegularExpressionAttribute
コード例 #1
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            try
            {
                Person contact = (Person)validationContext.ObjectInstance;
                if (contact.Category != Person.Supplier)
                {
                    return(ValidationResult.Success);
                }

                RequiredAttribute required = new RequiredAttribute();
                if (!required.IsValid(value))
                {
                    return(new ValidationResult($"Telephone is required for a {Person.Supplier}."));
                }

                RegularExpressionAttribute regex = new RegularExpressionAttribute(Pattern);
                if (!regex.IsValid(value))
                {
                    return(new ValidationResult($"Telephone number should be at least 7 and no more than 12 digits."));
                }
            }
            catch (Exception ex)
            {
                return(new ValidationResult("Somrthing wrong while validating Telephone Number!" + ex.Message));
            }

            return(ValidationResult.Success);
        }
コード例 #2
0
        public void ClientRulesWithRegexAttribute()
        {
            // Arrange
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(
                () => null,
                typeof(string),
                "Length"
                );
            var context   = new ControllerContext();
            var attribute = new RegularExpressionAttribute("the_pattern");
            var adapter   = new RegularExpressionAttributeAdapter(metadata, context, attribute);

            // Act
            var rules = adapter.GetClientValidationRules().OrderBy(r => r.ValidationType).ToArray();

            // Assert
            ModelClientValidationRule rule = Assert.Single(rules);

            Assert.Equal("regex", rule.ValidationType);
            Assert.Single(rule.ValidationParameters);
            Assert.Equal("the_pattern", rule.ValidationParameters["pattern"]);
            Assert.Equal(
                @"The field Length must match the regular expression 'the_pattern'.",
                rule.ErrorMessage
                );
        }
コード例 #3
0
        public void IsCultureCodeValidTests()
        {
            var attribute = new RegularExpressionAttribute(Expressions.CultureCode);

            Assert.IsTrue(attribute.IsValid(null));
            Assert.IsTrue(attribute.IsValid(string.Empty));
            Assert.IsTrue(attribute.IsValid("ab"));
            Assert.IsTrue(attribute.IsValid("XYZ"));
            Assert.IsTrue(attribute.IsValid("ab-WxYz"));
            Assert.IsTrue(attribute.IsValid("abc-wXyZ"));
            Assert.IsTrue(attribute.IsValid("ab-cd"));
            Assert.IsTrue(attribute.IsValid("UVW-XYZ"));
            Assert.IsTrue(attribute.IsValid("ab-123"));
            Assert.IsTrue(attribute.IsValid("XYZ-789"));
            Assert.IsTrue(attribute.IsValid("ab-CD-Efgh"));
            Assert.IsTrue(attribute.IsValid("UVW-XYZ-abcd"));
            Assert.IsTrue(attribute.IsValid("ab-123-cdef"));
            Assert.IsTrue(attribute.IsValid("XYZ-789-abcd"));

            Assert.IsFalse(attribute.IsValid("12"));
            Assert.IsFalse(attribute.IsValid("789"));
            Assert.IsFalse(attribute.IsValid("6789"));
            Assert.IsFalse(attribute.IsValid("A"));
            Assert.IsFalse(attribute.IsValid("AB-"));
            Assert.IsFalse(attribute.IsValid("WXYZ"));
            Assert.IsFalse(attribute.IsValid("AB-789-XYZ"));
            Assert.IsFalse(attribute.IsValid("AB-789-VWXYZ"));
            Assert.IsFalse(attribute.IsValid("UVW-XYZ-0000"));
        }
コード例 #4
0
        public static void MatchTimeoutInMilliseconds_GetSet_ReturnsExpected(int newValue)
        {
            var attribute = new RegularExpressionAttribute("SomePattern");

            attribute.MatchTimeoutInMilliseconds = newValue;
            Assert.Equal(newValue, attribute.MatchTimeoutInMilliseconds);
        }
コード例 #5
0
        private bool ValidateRegularExpression(string propertyName, ObjectDefPropertyValidation mpv)
        {
            ValidationAttribute attr = new RegularExpressionAttribute(mpv.Expression);
            ObjectDefInstanceValidationAttribute target = new ObjectDefInstanceValidationAttribute(attr, _mv);

            return(target.IsValid(propertyName));
        }
コード例 #6
0
        /// <summary>
        /// Creates the validator.
        /// </summary>
        /// <param name="modelMetadata">The model metadata.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        protected override ModelValidator CreateValidatorCore(ExtendedModelMetadata modelMetadata, ControllerContext context)
        {
            var attribute = new RegularExpressionAttribute(Pattern);

            PopulateErrorMessage(attribute);
            return(new RegularExpressionAttributeAdapter(modelMetadata, context, attribute));
        }
コード例 #7
0
        public void IsValid_NonStringValue()
        {
            RegularExpressionAttribute numericValueValidation = new RegularExpressionAttribute("1234");

            Assert.IsTrue(numericValueValidation.IsValid(1234));
            Assert.IsFalse(numericValueValidation.IsValid(20.10));
        }
コード例 #8
0
        public void PrincipalBalanceOutstandingAmountTest_SelfReportedLoanModel_check_for_regex()
        {
            SelfReportedLoanModel passingValueTwoDecimalPlaces = new SelfReportedLoanModel()
            {
                PrincipalBalanceOutstandingAmount = 100.01m
            };
            SelfReportedLoanModel passingValueOneDecimalPlace = new SelfReportedLoanModel()
            {
                PrincipalBalanceOutstandingAmount = 100.1m
            };
            SelfReportedLoanModel passingValueNoDecimalPlaces = new SelfReportedLoanModel()
            {
                PrincipalBalanceOutstandingAmount = 100m
            };
            SelfReportedLoanModel failingValueImproperNumberOfDigits = new SelfReportedLoanModel()
            {
                PrincipalBalanceOutstandingAmount = 100.001m
            };


            RegularExpressionAttribute regexCheck = new RegularExpressionAttribute(RegexStrings.CURRENCY);


            Assert.IsTrue(regexCheck.IsValid(passingValueTwoDecimalPlaces.PrincipalBalanceOutstandingAmount), "Assertion of positive case (2 decimal places) being true failed");
            Assert.IsTrue(regexCheck.IsValid(passingValueNoDecimalPlaces.PrincipalBalanceOutstandingAmount), "Assertion of positive case (0 decimal places) being true failed");
            Assert.IsTrue(regexCheck.IsValid(passingValueOneDecimalPlace.PrincipalBalanceOutstandingAmount), "Assertion of positive case (1 decimal place) being true failed");
            Assert.IsFalse(regexCheck.IsValid(failingValueImproperNumberOfDigits.PrincipalBalanceOutstandingAmount), "Assertion of negative case (improper # of digits) case being false failed");
        }
コード例 #9
0
 /// <summary>
 /// Указывает, что значение поля должно соответствовать регулярному выражению, если другое поле имеет необходимое значение
 /// </summary>
 /// <param name="fieldName">Название "контроллирующего" поля модели и группы радиобаттонов на странице</param>
 /// <param name="valueToCompare">Значение, которое должно иметь "контроллирующее" поле</param>
 /// <param name="pattern">Регулярное выражение</param>
 public RegularExpressionByRadioButtonAttribute(string fieldName, int valueToCompare, string pattern)
 {
     this.fieldName             = fieldName;
     this.valueToCompare        = valueToCompare.ToString();
     this.pattern               = pattern;
     regularExpressionAttribute = new RegularExpressionAttribute(pattern);
 }
コード例 #10
0
        public static RegularExpressionAttribute CreateRegularExpressionAttribute(string pattern, string errorMessage)
        {
            var returnValue = new RegularExpressionAttribute(pattern);

            UpdateErrorMessage(returnValue, errorMessage);
            return(returnValue);
        }
コード例 #11
0
        public void EmptyGuidShouldFailRegex()
        {
            RegularExpressionAttribute
                attribute = new RegularExpressionAttribute(ExampleModel.EmptyGuidValidationRegex);

            Assert.False(attribute.IsValid(Guid.Empty));
        }
コード例 #12
0
        public void CreateValidationMetadata(ValidationMetadataProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (context.Key.ContainerType != null && !context.Key.ContainerType.IsValueType)
            {
                var viewConfig = ServiceLocator.GetViewConfigure(context.Key.ContainerType);

                if (viewConfig != null && context.Key.Name.IsNotNullAndWhiteSpace())
                {
                    var descriptor = viewConfig.GetViewPortDescriptor(context.Key.Name);
                    if (descriptor != null)
                    {
                        descriptor.Validator.Each(v =>
                        {
                            v.DisplayName = descriptor.DisplayName;
                            if (v is RangeValidator)
                            {
                                RangeValidator valid = (RangeValidator)v;
                                RangeAttribute range = new RangeAttribute(valid.Min, valid.Max);
                                range.ErrorMessage   = valid.ErrorMessage;

                                context.ValidationMetadata.ValidatorMetadata.Add(range);
                            }
                            else if (v is RegularValidator)
                            {
                                RegularValidator valid             = (RegularValidator)v;
                                RegularExpressionAttribute regular = new RegularExpressionAttribute(valid.Expression);
                                regular.ErrorMessage = valid.ErrorMessage;
                                context.ValidationMetadata.ValidatorMetadata.Add(regular);
                            }
                            else if (v is RemoteValidator)
                            {
                                RemoteValidator valid  = (RemoteValidator)v;
                                RemoteAttribute remote = new RemoteAttribute(valid.Action, valid.Controller, valid.Area);
                                remote.ErrorMessage    = valid.ErrorMessage;
                                context.ValidationMetadata.ValidatorMetadata.Add(remote);
                            }
                            else if (v is RequiredValidator)
                            {
                                RequiredValidator valid    = (RequiredValidator)v;
                                RequiredAttribute required = new RequiredAttribute();
                                required.ErrorMessage      = valid.ErrorMessage;
                                context.ValidationMetadata.ValidatorMetadata.Add(required);
                            }
                            else if (v is StringLengthValidator)
                            {
                                StringLengthValidator valid        = (StringLengthValidator)v;
                                StringLengthAttribute stringLength = new StringLengthAttribute(valid.Max);
                                stringLength.ErrorMessage          = valid.ErrorMessage;
                                context.ValidationMetadata.ValidatorMetadata.Add(stringLength);
                            }
                        });
                    }
                }
            }
        }
コード例 #13
0
        public void Constructor_NullPattern()
        {
            var attr = new RegularExpressionAttribute(null);

            ExceptionHelper.ExpectException <InvalidOperationException>(delegate() {
                attr.IsValid("");
            }, Resources.DataAnnotationsResources.RegularExpressionAttribute_Empty_Pattern);
        }
コード例 #14
0
        public void Constructor_InvalidPattern()
        {
            var attr = new RegularExpressionAttribute("(");

            // Cannot test the exception message, because on the non-developer runtime of Silverlight
            // the exception string is not available.
            ExceptionHelper.ExpectArgumentException(() => attr.IsValid(""), null);
        }
コード例 #15
0
        private void ShouldReturnEmptyEnumerableMetadata(
            RequiredMetaProvider patternMetaProvider,
            RegularExpressionAttribute attribute)
        {
            var meta = patternMetaProvider.GetMetadata(attribute).ToArray();

            Assert.True(meta.Length == 0);
        }
コード例 #16
0
        public PasswordValidationAttribute()
        {
            var configuration = DependencyResolver.Current.GetService <IGalleryConfigurationService>().Current;

            _regexAttribute = new RegularExpressionAttribute(configuration.UserPasswordRegex)
            {
                ErrorMessage = configuration.UserPasswordHint
            };
        }
コード例 #17
0
        public static void Validate_MatchingTimesOut_ThrowsRegexMatchTimeoutException()
        {
            RegularExpressionAttribute attribute = new RegularExpressionAttribute("(a[ab]+)+$")
            {
                MatchTimeoutInMilliseconds = 1
            };

            Assert.Throws <RegexMatchTimeoutException>(() => attribute.Validate("aaaaaaaaaaaaaaaaaaaaaaaaaaaa>", new ValidationContext(new object())));
        }
コード例 #18
0
        public static void Validate_InvalidMatchTimeoutInMilliseconds_ThrowsArgumentOutOfRangeException(int timeout)
        {
            RegularExpressionAttribute attribute = new RegularExpressionAttribute("[^a]+\\.[^z]+")
            {
                MatchTimeoutInMilliseconds = timeout
            };

            AssertExtensions.Throws <ArgumentOutOfRangeException>("matchTimeout", () => attribute.Validate("a", new ValidationContext(new object())));
        }
コード例 #19
0
        public static void MatchTimeout_Get_ReturnsExpected(int newValue)
        {
            var attribute = new RegularExpressionAttribute("SomePattern")
            {
                MatchTimeoutInMilliseconds = newValue
            };

            Assert.Equal(TimeSpan.FromMilliseconds(newValue), attribute.MatchTimeout);
        }
コード例 #20
0
        /// <summary>
        /// 初始化 <see cref="RegularExpressionValidatorAttribute"/> 类的新实例。
        /// </summary>
        /// <param name="pattern">用于验证数据字段值的正则表达式。</param>
        public RegularExpressionValidatorAttribute(string pattern) : base(ResourceUtility.GetString("${Text.RegularExpressionValidator.ValidationError}"))
        {
            if (string.IsNullOrEmpty(pattern))
            {
                throw new ArgumentNullException(pattern);
            }

            _regularExpressionAttribute = new RegularExpressionAttribute(pattern);
        }
コード例 #21
0
 private string BuildValidationWithMaxLengthAttribute(RegularExpressionAttribute regexpAtribute, string propertyName)
 {
     return
         (string.Format(
              @"model['{0}'].extend({{
                  pattern: {{
                             message: '{2}',
                             params: /{1}/
                             }} }});", propertyName, regexpAtribute.Pattern, regexpAtribute.LocalizableError()));
 }
コード例 #22
0
        public LocalizedRegularExpressionAttribute(RegularExpressionAttribute attribute, Localizer t)
            : base(attribute.Pattern)
        {
            if (!String.IsNullOrEmpty(attribute.ErrorMessage))
            {
                ErrorMessage = attribute.ErrorMessage;
            }

            T = t;
        }
コード例 #23
0
        private static void ValidateRegularExpressionAttribute(RegularExpressionAttribute attribute, PropertyInfo property, T model)
        {
            string value = (property.GetValue(model, null) ?? string.Empty).ToString();

            if (Regex.IsMatch(value, attribute.Pattern))
            {
                return;
            }
            // TODO: Add descriptive error message default
            throw new ModelValidationException(property.Name, value, attribute.ErrorMessage);
        }
コード例 #24
0
        /// <summary>
        /// Adds a RegularExpressionAttribute.
        /// </summary>
        /// <param name="pattern">Regular expression used to validate value.</param>
        /// <param name="errMsg">Gets or sets an error message to associate with a validation control if validation fails.</param>
        /// <returns></returns>
        public BaValidatorList RegularExpression(string pattern, string errMsg = null)
        {
            var att = new RegularExpressionAttribute(pattern);

            if (errMsg != null)
            {
                att.ErrorMessage = errMsg;
            }
            Add(att);
            return(this);
        }
コード例 #25
0
        public void Setup()
        {
            var attribute1 = new StringLengthAttribute(5);

            attribute1.ErrorMessage = "length";
            var attribute2 = new RegularExpressionAttribute("a*");

            attribute2.ErrorMessage = "regex";

            this.validator = new ValidationAttributeValidator(attribute1, attribute2);
        }
コード例 #26
0
 public override bool IsValid(object value)
 {
     if (value != null)
     {
         var regexValidator = new RegularExpressionAttribute(_pattern);
         if (!regexValidator.IsValid(value))
         {
             return(false);
         }
     }
     return(true);
 }
コード例 #27
0
        public void Given_RegularExpressionAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(string pattern)
        {
            var name      = "hello";
            var acceptor  = new OpenApiSchemaAcceptor();
            var type      = new KeyValuePair <string, Type>(name, typeof(DateTime));
            var attribute = new RegularExpressionAttribute(pattern);

            this._visitor.Visit(acceptor, type, this._strategy, attribute);

            acceptor.Schemas.Should().ContainKey(name);
            acceptor.Schemas[name].Type.Should().Be("string");
            acceptor.Schemas[name].Pattern.Should().Be(pattern);
        }
コード例 #28
0
        private ValidationAttribute CopyAttribute(ValidationAttribute attribute)
        {
            ValidationAttribute result = null;

            if (attribute is RangeAttribute)
            {
                var attr = (RangeAttribute)attribute;
                result = (attr.Minimum is double)
                                        ?  new RangeAttribute((double)attr.Minimum, (double)attr.Maximum)
                                        :  new RangeAttribute((int)attr.Minimum, (int)attr.Maximum);
            }

            if (attribute is RegularExpressionAttribute)
            {
                var attr = (RegularExpressionAttribute)attribute;
                result = new RegularExpressionAttribute(attr.Pattern);
            }

            if (attribute is RequiredAttribute)
            {
                result = new RequiredAttribute();
            }

            if (attribute is StringLengthAttribute)
            {
                var attr = (StringLengthAttribute)attribute;
                result = new StringLengthAttribute(attr.MaximumLength)
                {
                    MinimumLength = attr.MinimumLength
                };
            }

            if (attribute is DA.CompareAttribute)
            {
                var attr = (DA.CompareAttribute)attribute;
                result = new DA.CompareAttribute(attr.OtherProperty);
            }

            if (attribute is DataTypeAttribute)
            {
                var attr = (DataTypeAttribute)attribute;
                result = new DataTypeAttribute(attr.DataType);
            }

            if (result == null && attribute.GetType().GetInterfaces().Contains(typeof(ICloneable)))
            {
                result = ((ICloneable)attribute).Clone() as ValidationAttribute;
            }

            return(result);
        }
コード例 #29
0
        private void ShouldReturnMetadata_PatternAttribute(
            PatternMetaProvider patternMetaProvider,
            [Frozen] string pattern,
            RegularExpressionAttribute regExAttribute)
        {
            var meta = patternMetaProvider.GetMetadata(regExAttribute).ToArray();

            Assert.Contains(meta, mp =>
            {
                var(key, value) = mp;

                return(key == "pattern" && (value as string) == pattern);
            });
        }
コード例 #30
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var pageUrl = value as string;

            if (!string.IsNullOrWhiteSpace(pageUrl))
            {
                var regExpAttribute = new RegularExpressionAttribute(PagesConstants.InternalUrlRegularExpression);
                if (!regExpAttribute.IsValid(pageUrl))
                {
                    return(new ValidationResult(errorMessage));
                }
            }

            return(ValidationResult.Success);
        }
コード例 #31
0
 public static void Ctor_String(string pattern)
 {
     var attribute = new RegularExpressionAttribute(pattern);
     Assert.Equal(pattern, attribute.Pattern);
 }
コード例 #32
0
 public static void MatchTimeoutInMilliseconds_GetSet_ReturnsExpected(int newValue)
 {
     var attribute = new RegularExpressionAttribute("SomePattern");
     attribute.MatchTimeoutInMilliseconds = newValue;
     Assert.Equal(newValue, attribute.MatchTimeoutInMilliseconds);
 }
コード例 #33
0
 public static void Validate_InvalidPattern_ThrowsInvalidOperationException(string pattern)
 {
     var attribute = new RegularExpressionAttribute(pattern);
     Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object())));
 }
コード例 #34
0
 public static void Validate_InvalidPattern_ThrowsArgumentException()
 {
     RegularExpressionAttribute attribute = new RegularExpressionAttribute("foo(?<1bar)");
     Assert.Throws<ArgumentException>(null, () => attribute.Validate("Any", new ValidationContext(new object())));
 }
コード例 #35
0
 public static void Validate_MatchingTimesOut_ThrowsRegexMatchTimeoutException()
 {
     RegularExpressionAttribute attribute = new RegularExpressionAttribute("(a+)+$") { MatchTimeoutInMilliseconds = 1 };
     Assert.Throws<RegexMatchTimeoutException>(() => attribute.Validate("aaaaaaaaaaaaaaaaaaaaaaaaaaaa>", new ValidationContext(new object())));
 }
コード例 #36
0
 public static void Validate_InvalidMatchTimeoutInMilliseconds_ThrowsArgumentOutOfRangeException(int timeout)
 {
     RegularExpressionAttribute attribute = new RegularExpressionAttribute("[^a]+\\.[^z]+") { MatchTimeoutInMilliseconds = 0 };
     Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => attribute.Validate("a", new ValidationContext(new object())));
 }