public void GetClientValidationRules_ReturnsValidationParameters_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RequiredAttribute();

            var expectedProperties = new object[] { "Length" };
            var message = "This paramter is required.";
            var expectedMessage = "FR This parameter is required.";
            attribute.ErrorMessage = message;

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("required", rule.ValidationType);
            Assert.Empty(rule.ValidationParameters);
            Assert.Equal(expectedMessage, rule.ErrorMessage);
        }
        public void AddValidation_AddsValidation_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RequiredAttribute();

            var expectedProperties = new object[] { "Length" };
            var message = "This paramter is required.";
            var expectedMessage = "FR This parameter is required.";
            attribute.ErrorMessage = message;

            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
                .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); });
        }
        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // Arrange
            var expectedMessage = ValidationAttributeUtil.GetRequiredErrorMessage("Length");
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new RequiredAttribute();
            var adapter = new RequiredAttributeAdapter(attribute, stringLocalizer: null);

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-required", "original");

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-required", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
 // ReSharper restore NotAccessedField.Local
 public TypePropertyValidationRuleMetadata(RequiredAttribute attribute)
     : this((ValidationAttribute) attribute)
 {
     Name = "required";
     Value1 = true;
     _type = "boolean";
 }
Пример #5
0
		public void AllowEmptyStrings ()
		{
			var attr = new RequiredAttribute ();

			Assert.IsFalse (attr.AllowEmptyStrings, "#A1");
			attr.AllowEmptyStrings = true;
			Assert.IsTrue (attr.AllowEmptyStrings, "#A2");
		}
        public LocalizedRequiredAttribute(RequiredAttribute attribute, Localizer t) {
            AllowEmptyStrings = attribute.AllowEmptyStrings;

            if ( !String.IsNullOrEmpty(attribute.ErrorMessage) )
                ErrorMessage = attribute.ErrorMessage;

            T = t;
        }
 public PizzaRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage) && string.IsNullOrEmpty(attribute.ErrorMessageResourceName))
     {
         attribute.ErrorMessage = Errors.ValueIsRequired;
     }
 }
Пример #8
0
 public ResourseBaseRequiredAttributeAdapter(ModelMetadata metadata,
                                   ControllerContext context,
                                   RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
     attribute.ErrorMessageResourceType = typeof(AvicolaGlobalResources);
     attribute.ErrorMessageResourceName = "Required";
 }
 public WeeeRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
 : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage) &&
         !string.IsNullOrEmpty(metadata.DisplayName))
     {
         attribute.ErrorMessage = string.Format("Enter {0}", metadata.DisplayName.ToLower());
     }
 }
Пример #10
0
 public CustomizedRequiredValidatorAdapter(ModelMetadata metadata,
                             ControllerContext context,
                             RequiredAttribute attribute)
     : base(metadata, context, attribute)
 {
     attribute.ErrorMessage = "Please enter value in {0}.";
     //attribute.ErrorMessageResourceType = typeof(Messages);
     //attribute.ErrorMessageResourceName = "PropertyValueRequired";
 }
 public static void Can_get_and_set_AllowEmptyStrings()
 {
     var attribute = new RequiredAttribute();
     Assert.False(attribute.AllowEmptyStrings);
     attribute.AllowEmptyStrings = true;
     Assert.True(attribute.AllowEmptyStrings);
     attribute.AllowEmptyStrings = false;
     Assert.False(attribute.AllowEmptyStrings);
 }
Пример #12
0
        public override ModelValidator Create(IStorageValidator validator, Type defaultResourceType, ModelMetadata metadata, ControllerContext context)
        {
            metadata.IsRequired = false;

            var attribute = new RequiredAttribute();
            this.BindErrorMessageToAttribte(attribute, validator, defaultResourceType);

            return new RequiredAttributeAdapter(metadata, context, attribute);
        }
Пример #13
0
		public void IsRequired ()
		{
			var attr = new RequiredAttribute ();
			Assert.IsFalse (attr.IsValid (null), "#A1");
			Assert.IsFalse (attr.IsValid (String.Empty), "#A2");
			Assert.IsTrue (attr.IsValid ("string"), "#A3");
			Assert.IsTrue (attr.IsValid (1), "#A4");
			attr.AllowEmptyStrings = true;
			Assert.IsTrue (attr.IsValid (String.Empty), "#A5");
		}
        public void ValuesSet()
        {
            // Arrange
            var attribute = new RequiredAttribute();

            // Act
            var validator = new DataAnnotationsModelValidator(attribute);

            // Assert
            Assert.Same(attribute, validator.Attribute);
        }
        public void Constructor_SetsAttribute()
        {
            // Arrange
            var attribute = new RequiredAttribute();

            // Act
            var validator = new DataAnnotationsModelValidator(attribute, stringLocalizer : null);

            // Assert
            Assert.Same(attribute, validator.Attribute);
        }
        public void ValuesSet()
        {
            // Arrange
            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), "Length");
            var attribute = new RequiredAttribute();

            // Act
            var validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute);

            // Assert
            Assert.Same(attribute, validator.Attribute);
        }
 public LocalizedRequiredAttributeAdapter(
     ModelMetadata metadata,
     ControllerContext context,
     RequiredAttribute attribute
 )
     : base(metadata, context, attribute)
 {
     if (attribute.ErrorMessageResourceType == null)
         attribute.ErrorMessageResourceType = typeof(Resources.Resources);
     if (attribute.ErrorMessageResourceName == null)
         attribute.ErrorMessageResourceName = "PropertyValueRequired";
 }
Пример #18
0
        public void RequiredAdapter_SetsErrorMessage()
        {
            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider()
                .GetMetadataForProperty(null, typeof(AdaptersModel), "Required");
            RequiredAttribute attribute = new RequiredAttribute();
            new RequiredAdapter(metadata, new ControllerContext(), attribute);

            String expected = Validations.FieldIsRequired;
            String actual = attribute.ErrorMessage;

            Assert.Equal(expected, actual);
        }
        public void NoClientRulesByDefault() {
            // Arrange
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), "Length");
            ControllerContext context = new ControllerContext();
            RequiredAttribute attribute = new RequiredAttribute();

            // Act
            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute);

            // Assert
            Assert.IsFalse(validator.GetClientValidationRules().Any());
        }
        private void Include()
        {
            ValidationAttribute attribute = new RequiredAttribute();
            var validationContext = new ValidationContext(this, null, new Dictionary<object, object>());
            validationContext.DisplayName = validationContext.DisplayName;
            validationContext.Items.Add(null, null);
            validationContext.MemberName = validationContext.MemberName;
            validationContext.ObjectInstance.GetHashCode();

            ValidationResult result = attribute.GetValidationResult(this, validationContext);
            result.ErrorMessage = result.ErrorMessage;
            result.MemberNames.GetHashCode();
        }
 public MyRequiredAttributeAdapter(
     ModelMetadata metadata,
     ControllerContext context,
     RequiredAttribute attribute
 )
     : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage))
     {
         attribute.ErrorMessageResourceType = typeof(Resources.UI);
         attribute.ErrorMessageResourceName = "PropertyValueRequired";
     }
 }
 public CustomRequiredAttribute(
     ModelMetadata metadata,
     ControllerContext context,
     RequiredAttribute attribute
     )
     : base(metadata, context, attribute)
 {
     if (string.IsNullOrEmpty(attribute.ErrorMessage))
     {
         attribute.ErrorMessageResourceType = typeof(DefaultResource);
         attribute.ErrorMessageResourceName = "PropertyValueRequired";
     }
 }
        public void ValuesSet() {
            // Arrange
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), "Length");
            ControllerContext context = new ControllerContext();
            RequiredAttribute attribute = new RequiredAttribute();

            // Act
            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute);

            // Assert
            Assert.AreSame(attribute, validator.Attribute);
            Assert.AreEqual(attribute.FormatErrorMessage("Length"), validator.ErrorMessage);
        }
        public void ConstructorGuards()
        {
            // Arrange
            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(object));
            var attribute = new RequiredAttribute();

            // Act & Assert
            Assert.ThrowsArgumentNull(
                () => new DataAnnotationsModelValidator(null, attribute),
                "validatorProviders");
            Assert.ThrowsArgumentNull(
                () => new DataAnnotationsModelValidator(_noValidatorProviders, null),
                "attribute");
        }
        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {            
            base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
            
            var metadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];
            var key = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);

            bool hasFormatException = false;

            ModelState state;            
            if (bindingContext.ModelState.TryGetValue(key, out state))
            {                                
                foreach (var err in state.Errors.Where(x => x.Exception != null).ToList())
                {
                    for (var inner = err.Exception; inner != null; inner = inner.InnerException)
                    {
                        if (inner is FormatException)
                        {                            
                            hasFormatException = true;
                            //DefaultModelBinder.BindProperty shouldn't consider this (thanks Reflector)
                            var msg = ExceptionHelper.LocalizeValidationException(TextManager, inner, metadata, 
                                value: state.Value);
                            if (!string.IsNullOrEmpty(msg))
                            {
                                state.Errors.Remove(err);
                                state.Errors.Add(msg);
                            }
                        }                        
                    }
                }
            }


            //Replace required message for non nullable types (again, thanks Reflector)
            var type = propertyDescriptor.PropertyType;
            bool nonNullable = type.IsValueType && Nullable.GetUnderlyingType(type) == null;
            if (nonNullable && value == null && !hasFormatException )
            {                
                //"Simulate" RequiredAttribute on property
                var attr = new RequiredAttribute();
                var msg = ExceptionHelper.LocalizeValidationException(TextManager, new ValidationException("", attr, value), metadata);
                
                if (msg != null)
                {
                    bindingContext.ModelState.Remove(key);
                    bindingContext.ModelState.AddModelError(key, msg);
                }
            }            
        }
Пример #26
0
        public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
            if (!string.IsNullOrWhiteSpace(Attribute.ErrorMessage)) return;

            if (Attribute.ErrorMessageResourceType == null)
            {
                Attribute.ErrorMessageResourceType = typeof (Message);
            }

            if (string.IsNullOrWhiteSpace(Attribute.ErrorMessageResourceName))
            {
                Attribute.ErrorMessageResourceName = "PropertyValueRequired";
            }
        }
        public void ConstructorGuards() {
            // Arrange
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));
            ControllerContext context = new ControllerContext();
            RequiredAttribute attribute = new RequiredAttribute();

            // Act & Assert
            ExceptionHelper.ExpectArgumentNullException(
                () => new DataAnnotationsModelValidator(null, context, attribute),
                "metadata");
            ExceptionHelper.ExpectArgumentNullException(
                () => new DataAnnotationsModelValidator(metadata, null, attribute),
                "controllerContext");
            ExceptionHelper.ExpectArgumentNullException(
                () => new DataAnnotationsModelValidator(metadata, context, null),
                "attribute");
        }
Пример #28
0
        private ValidationAttribute CopyAttribute(ValidationAttribute attribute)
        {
            ValidationAttribute result = null;

            if (attribute is RangeAttribute)
            {
                var attr = (RangeAttribute)attribute;
                result = new RangeAttribute((double)attr.Minimum, (double)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 CompareAttribute)
            {
                var attr = (CompareAttribute)attribute;
                result = new 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;
        }
        public void ClientRulesWithRequiredAttribute() {
            // Arrange
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), "Length");
            var context = new ControllerContext();
            var attribute = new RequiredAttribute();
            var adapter = new RequiredAttribute4Adapter(metadata, context, attribute);

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

            // Assert
            Assert.AreEqual(1, rules.Length);
            Assert.AreEqual("required", rules[0].ValidationType);
            Assert.AreEqual(0, rules[0].ValidationParameters.Count);
            Assert.AreEqual(@"The Length field is required.", rules[0].ErrorMessage);
        }
Пример #30
0
        public void GetClientValidationRules_ReturnsValidationParameters()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new RequiredAttribute();
            var adapter = new RequiredAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("required", rule.ValidationType);
            Assert.Empty(rule.ValidationParameters);
            Assert.Equal("The Length field is required.", rule.ErrorMessage);
        }
Пример #31
0
        private static IEnumerable <ValidationError> GetValidationErrors(object value, ValidationContext validationContext, IEnumerable <ValidationAttribute> attributes, bool breakOnFirstError)
        {
            if (validationContext == null)
            {
                throw new ArgumentNullException("validationContext");
            }

            List <ValidationError> errors = new List <ValidationError>();
            ValidationError        validationError;

            // Get the required validator if there is one and test it first, aborting on failure
            System.ComponentModel.DataAnnotations.RequiredAttribute required = attributes.FirstOrDefault(a => a is System.ComponentModel.DataAnnotations.RequiredAttribute) as System.ComponentModel.DataAnnotations.RequiredAttribute;
            if (required != null)
            {
                if (!TryValidate(value, validationContext, required, out validationError))
                {
                    errors.Add(validationError);
                    return(errors);
                }
            }

            // Iterate through the rest of the validators, skipping the required validator
            foreach (ValidationAttribute attr in attributes)
            {
                if (attr != required)
                {
                    if (!TryValidate(value, validationContext, attr, out validationError))
                    {
                        errors.Add(validationError);

                        if (breakOnFirstError)
                        {
                            break;
                        }
                    }
                }
            }

            return(errors);
        }