Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.
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); }
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 ); }
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")); }
public static void MatchTimeoutInMilliseconds_GetSet_ReturnsExpected(int newValue) { var attribute = new RegularExpressionAttribute("SomePattern"); attribute.MatchTimeoutInMilliseconds = newValue; Assert.Equal(newValue, attribute.MatchTimeoutInMilliseconds); }
private bool ValidateRegularExpression(string propertyName, ObjectDefPropertyValidation mpv) { ValidationAttribute attr = new RegularExpressionAttribute(mpv.Expression); ObjectDefInstanceValidationAttribute target = new ObjectDefInstanceValidationAttribute(attr, _mv); return(target.IsValid(propertyName)); }
/// <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)); }
public void IsValid_NonStringValue() { RegularExpressionAttribute numericValueValidation = new RegularExpressionAttribute("1234"); Assert.IsTrue(numericValueValidation.IsValid(1234)); Assert.IsFalse(numericValueValidation.IsValid(20.10)); }
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"); }
/// <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); }
public static RegularExpressionAttribute CreateRegularExpressionAttribute(string pattern, string errorMessage) { var returnValue = new RegularExpressionAttribute(pattern); UpdateErrorMessage(returnValue, errorMessage); return(returnValue); }
public void EmptyGuidShouldFailRegex() { RegularExpressionAttribute attribute = new RegularExpressionAttribute(ExampleModel.EmptyGuidValidationRegex); Assert.False(attribute.IsValid(Guid.Empty)); }
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); } }); } } } }
public void Constructor_NullPattern() { var attr = new RegularExpressionAttribute(null); ExceptionHelper.ExpectException <InvalidOperationException>(delegate() { attr.IsValid(""); }, Resources.DataAnnotationsResources.RegularExpressionAttribute_Empty_Pattern); }
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); }
private void ShouldReturnEmptyEnumerableMetadata( RequiredMetaProvider patternMetaProvider, RegularExpressionAttribute attribute) { var meta = patternMetaProvider.GetMetadata(attribute).ToArray(); Assert.True(meta.Length == 0); }
public PasswordValidationAttribute() { var configuration = DependencyResolver.Current.GetService <IGalleryConfigurationService>().Current; _regexAttribute = new RegularExpressionAttribute(configuration.UserPasswordRegex) { ErrorMessage = configuration.UserPasswordHint }; }
public static void Validate_MatchingTimesOut_ThrowsRegexMatchTimeoutException() { RegularExpressionAttribute attribute = new RegularExpressionAttribute("(a[ab]+)+$") { MatchTimeoutInMilliseconds = 1 }; Assert.Throws <RegexMatchTimeoutException>(() => attribute.Validate("aaaaaaaaaaaaaaaaaaaaaaaaaaaa>", new ValidationContext(new object()))); }
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()))); }
public static void MatchTimeout_Get_ReturnsExpected(int newValue) { var attribute = new RegularExpressionAttribute("SomePattern") { MatchTimeoutInMilliseconds = newValue }; Assert.Equal(TimeSpan.FromMilliseconds(newValue), attribute.MatchTimeout); }
/// <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); }
private string BuildValidationWithMaxLengthAttribute(RegularExpressionAttribute regexpAtribute, string propertyName) { return (string.Format( @"model['{0}'].extend({{ pattern: {{ message: '{2}', params: /{1}/ }} }});", propertyName, regexpAtribute.Pattern, regexpAtribute.LocalizableError())); }
public LocalizedRegularExpressionAttribute(RegularExpressionAttribute attribute, Localizer t) : base(attribute.Pattern) { if (!String.IsNullOrEmpty(attribute.ErrorMessage)) { ErrorMessage = attribute.ErrorMessage; } T = t; }
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); }
/// <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); }
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); }
public override bool IsValid(object value) { if (value != null) { var regexValidator = new RegularExpressionAttribute(_pattern); if (!regexValidator.IsValid(value)) { return(false); } } return(true); }
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); }
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); }
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); }); }
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); }
public static void Ctor_String(string pattern) { var attribute = new RegularExpressionAttribute(pattern); Assert.Equal(pattern, attribute.Pattern); }
public static void Validate_InvalidPattern_ThrowsInvalidOperationException(string pattern) { var attribute = new RegularExpressionAttribute(pattern); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Any", new ValidationContext(new object()))); }
public static void Validate_InvalidPattern_ThrowsArgumentException() { RegularExpressionAttribute attribute = new RegularExpressionAttribute("foo(?<1bar)"); Assert.Throws<ArgumentException>(null, () => attribute.Validate("Any", new ValidationContext(new object()))); }
public static void Validate_MatchingTimesOut_ThrowsRegexMatchTimeoutException() { RegularExpressionAttribute attribute = new RegularExpressionAttribute("(a+)+$") { MatchTimeoutInMilliseconds = 1 }; Assert.Throws<RegexMatchTimeoutException>(() => attribute.Validate("aaaaaaaaaaaaaaaaaaaaaaaaaaaa>", new ValidationContext(new object()))); }
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()))); }