public void Validate_IsValidFalse_StringLocalizerReturnsLocalizerErrorMessage() { // Arrange var metadata = _metadataProvider.GetMetadataForType(typeof(string)); var container = "Hello"; var attribute = new MaxLengthAttribute(4); attribute.ErrorMessage = "{0} should have no more than {1} characters."; var localizedString = new LocalizedString(attribute.ErrorMessage, "Longueur est invalide : 4"); var stringLocalizer = new Mock <IStringLocalizer>(); stringLocalizer.Setup(s => s[attribute.ErrorMessage, It.IsAny <object[]>()]).Returns(localizedString); var validator = new DataAnnotationsModelValidator( new ValidationAttributeAdapterProvider(), attribute, stringLocalizer.Object); var validationContext = new ModelValidationContext( actionContext: new ActionContext(), modelMetadata: metadata, metadataProvider: _metadataProvider, container: container, model: "abcde"); // Act var result = validator.Validate(validationContext); // Assert var validationResult = result.Single(); Assert.Empty(validationResult.MemberName); Assert.Equal("Longueur est invalide : 4", validationResult.Message); }
public static MaxLengthAttribute CreateMaxLengthAttribute(int length, string errorMessage = null) { var returnValue = new MaxLengthAttribute(length); UpdateErrorMessage(returnValue, errorMessage); return(returnValue); }
public void MaxLengthAttribute_AddValidation_StringLocalizer_ReturnsLocalizedErrorString() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var errorKey = metadata.GetDisplayName(); var attribute = new MaxLengthAttribute(10); attribute.ErrorMessage = errorKey; var localizedString = new LocalizedString(errorKey, "Longueur est invalide"); var stringLocalizer = new Mock <IStringLocalizer>(); stringLocalizer.Setup(s => s[errorKey, metadata.GetDisplayName(), attribute.Length]).Returns(localizedString); var expectedMessage = "Longueur est invalide"; var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer.Object); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary <string, string>()); // 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-maxlength", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); }, kvp => { Assert.Equal("data-val-maxlength-max", kvp.Key); Assert.Equal("10", kvp.Value); }); }
public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new MaxLengthAttribute(10); var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer: null); var expectedMessage = attribute.FormatErrorMessage("Length"); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary <string, string>()); context.Attributes.Add("data-val", "original"); context.Attributes.Add("data-val-maxlength", "original"); context.Attributes.Add("data-val-maxlength-max", "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-maxlength", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-maxlength-max", kvp.Key); Assert.Equal("original", kvp.Value); }); }
public void ClientRulesWithMaxLengthAttributeAndCustomMessage() { // Arrange var propertyName = "Length"; var message = "{0} must be at most {1}"; var provider = new DataAnnotationsModelMetadataProvider(); var metadata = provider.GetMetadataForProperty(() => null, typeof(string), propertyName); var attribute = new MaxLengthAttribute(5) { ErrorMessage = message }; var adapter = new MaxLengthAttributeAdapter(attribute); var context = new ClientModelValidationContext(metadata, provider); // Act var rules = adapter.GetClientValidationRules(context); // Assert var rule = Assert.Single(rules); Assert.Equal("maxlength", rule.ValidationType); Assert.Equal(1, rule.ValidationParameters.Count); Assert.Equal(5, rule.ValidationParameters["max"]); Assert.Equal("Length must be at most 5", rule.ErrorMessage); }
public void MaxLengthAttribute_AddValidation_Localize() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new MaxLengthAttribute(10); attribute.ErrorMessage = "Property must be max '{1}' characters long."; var expectedProperties = new object[] { "Length", 10 }; var expectedMessage = "Property must be max '10' characters long."; var stringLocalizer = new Mock <IStringLocalizer>(); stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties]) .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage)); var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary <string, string>()); // 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-maxlength", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); }, kvp => { Assert.Equal("data-val-maxlength-max", kvp.Key); Assert.Equal("10", kvp.Value); }); }
public void ClientRulesWithMaxLengthAttribute_StringLocalizer_ReturnsLocalizedErrorString() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var errorKey = metadata.GetDisplayName(); var attribute = new MaxLengthAttribute(10); attribute.ErrorMessage = errorKey; var localizedString = new LocalizedString(errorKey, "Longueur est invalide"); var stringLocalizer = new Mock <IStringLocalizer>(); stringLocalizer.Setup(s => s[errorKey, metadata.GetDisplayName(), attribute.Length]).Returns(localizedString); var adapter = new MaxLengthAttributeAdapter(attribute, 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("maxlength", rule.ValidationType); Assert.Equal(1, rule.ValidationParameters.Count); Assert.Equal(10, rule.ValidationParameters["max"]); Assert.Equal("Longueur est invalide", rule.ErrorMessage); }
private static int GetMaxLengthFrom <T>(MaxLengthAttribute maxLengthAttribute, StringLengthAttribute stringLengthAttribute, PropertyData <T> propData) { if (stringLengthAttribute == null) { return(maxLengthAttribute.Length); } if (maxLengthAttribute == null) { return(stringLengthAttribute.MaximumLength); } if (stringLengthAttribute.MaximumLength == maxLengthAttribute.Length) { return(stringLengthAttribute.MaximumLength); } Assert.Fail(string.Join(string.Empty, "MaxLength and StringLength are both specified for '", propData.PropertyPath, "' on type '", propData.ParentType.PrettyName(), "' but disagree on the maximum length: ", maxLengthAttribute.Length, " vs ", stringLengthAttribute.MaximumLength )); throw new Exception("Should not get here as we should have Assert.Failed"); }
public void CreateWithStringRequestConstrainedbyMinAndMaxLengthReturnsCorrectResult(int min, int max) { // Arrange var minLengthAttribute = new MinLengthAttribute(min); var maxLengthAttribute = new MaxLengthAttribute(max); var request = new FakeMemberInfo( new ProvidedAttribute(minLengthAttribute, true), new ProvidedAttribute(maxLengthAttribute, true)); var expectedRequest = new ConstrainedStringRequest(min, max); var expectedResult = new object(); var context = new DelegatingSpecimenContext { OnResolve = r => expectedRequest.Equals(r) ? expectedResult : new NoSpecimen() }; var sut = new MinAndMaxLengthAttributeRelay { RequestMemberTypeResolver = new DelegatingRequestMemberTypeResolver { OnTryGetMemberType = r => typeof(string) } }; // Act var result = sut.Create(request, context); // Assert Assert.Equal(expectedResult, result); }
private string BuildValidationWithMaxLengthAttribute(MaxLengthAttribute maxAttribute, string propertyName) { return (string.Format( @"model['{0}'].extend({{ maxLength: {{ params: {1}, message: '{2}' }} }});", propertyName, maxAttribute.Length, maxAttribute.ErrorMessage)); }
public void MaxLengthAttribute_AddValidation_CustomMessage() { // Arrange var propertyName = "Length"; var message = "{0} must be at most {1}"; var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), propertyName); var expectedMessage = "Length must be at most 5"; var attribute = new MaxLengthAttribute(5) { ErrorMessage = message }; var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer: null); var actionContext = new ActionContext(); var context = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary <string, string>()); // 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-maxlength", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); }, kvp => { Assert.Equal("data-val-maxlength-max", kvp.Key); Assert.Equal("5", kvp.Value); }); }
public void ClientRulesWithMaxLengthAttributeAndCustomMessage() { // Arrange var propertyName = "Length"; var message = "{0} must be at most {1}"; var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), propertyName); var attribute = new MaxLengthAttribute(5) { ErrorMessage = message }; var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer: null); var serviceCollection = new ServiceCollection(); var requestServices = serviceCollection.BuildServiceProvider(); var context = new ClientModelValidationContext(metadata, provider, requestServices); // Act var rules = adapter.GetClientValidationRules(context); // Assert var rule = Assert.Single(rules); Assert.Equal("maxlength", rule.ValidationType); Assert.Equal(1, rule.ValidationParameters.Count); Assert.Equal(5, rule.ValidationParameters["max"]); Assert.Equal("Length must be at most 5", rule.ErrorMessage); }
public void ClientRulesWithMaxLengthAttribute() { // Arrange var metadata = ModelMetadataProviders.Current.GetMetadataForProperty( () => null, typeof(string), "Length" ); var context = new ControllerContext(); var attribute = new MaxLengthAttribute(10); var adapter = new MaxLengthAttributeAdapter(metadata, context, attribute); // Act var rules = adapter.GetClientValidationRules(); // Assert ModelClientValidationRule rule = Assert.Single(rules); Assert.Equal("maxlength", rule.ValidationType); Assert.Equal(1, rule.ValidationParameters.Count); Assert.Equal(10, rule.ValidationParameters["max"]); Assert.Equal( "The field Length must be a string or array type with a maximum length of '10'.", rule.ErrorMessage ); }
protected override void RenderEditMode(System.Web.UI.HtmlTextWriter writer) { int length = Null.NullInteger; if ((CustomAttributes != null)) { foreach (System.Attribute attribute in CustomAttributes) { if (attribute is MaxLengthAttribute) { MaxLengthAttribute lengthAtt = (MaxLengthAttribute)attribute; length = lengthAtt.Length; break; } } } ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Value, StringValue); if (length > Null.NullInteger) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); }
public void Add(Option newOption) { if (string.IsNullOrEmpty(newOption.Text)) { throw new ArgumentNullException(nameof(newOption.Text)); } List <PropertyInfo> props = typeof(Option) .GetProperties() .Where(p => p.GetCustomAttributes(typeof(MaxLengthAttribute), true).Any()).ToList(); MaxLengthAttribute max = props.First(p => p.Name == nameof(newOption.Text)) .GetCustomAttributes(true) .Where(attr => attr.GetType() == typeof(MaxLengthAttribute)) .FirstOrDefault() as MaxLengthAttribute; if (max != null) { if (max.Length < newOption.Text.Length) { throw new ArgumentOutOfRangeException(nameof(newOption.Text)); } } _context.Options.Add(newOption); _context.SaveChanges(); }
public static List <SqlParameter> GetSqlParameters <T>(T queryModel) { List <SqlParameter> sqlParameters = new List <SqlParameter>(); foreach (PropertyInfo p in queryModel.GetType().GetProperties()) { var val = p.GetValue(queryModel); SqlParameter sqlParameter = new SqlParameter(); if (p.PropertyType == typeof(string) && val != null) { Attribute attr = p.GetCustomAttribute(typeof(MaxLengthAttribute)); MaxLengthAttribute maxLengthAttribute = attr as MaxLengthAttribute; int size = maxLengthAttribute.Length; sqlParameter = new SqlParameter("@" + p.Name, SqlDbType.VarChar, size); sqlParameter.Value = val.ToString(); } if (p.PropertyType == typeof(int) && Convert.ToInt32(val) != 0) { sqlParameter = new SqlParameter("@" + p.Name, Convert.ToInt32(val)); } if (p.PropertyType == typeof(DateTime) && val != null && Convert.ToDateTime(val) != DateTime.MinValue) { sqlParameter = new SqlParameter("@" + p.Name, Convert.ToDateTime(val)); } sqlParameters.Add(sqlParameter); } return(sqlParameters); }
public void ClientRulesWithMaxLengthAttribute_Localize() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(string), "Length"); var attribute = new MaxLengthAttribute(10); attribute.ErrorMessage = "Property must be max '{1}' characters long."; var expectedProperties = new object[] { "Length", 10 }; var expectedMessage = "Property must be max '10' characters long."; var stringLocalizer = new Mock <IStringLocalizer>(); stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties]) .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage)); var adapter = new MaxLengthAttributeAdapter(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("maxlength", rule.ValidationType); Assert.Equal(1, rule.ValidationParameters.Count); Assert.Equal(10, rule.ValidationParameters["max"]); Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage); }
void InstantiateColumn(ref int currentPos, string StoragePath, string TableName, MemberInfo member, Type type, out int pos) { KeyAttribute key = (KeyAttribute)member.GetCustomAttribute(typeof(KeyAttribute)); StringLengthAttribute stringLength = (StringLengthAttribute)member.GetCustomAttribute(typeof(StringLengthAttribute)); MaxLengthAttribute maxLength = (MaxLengthAttribute)member.GetCustomAttribute(typeof(MaxLengthAttribute)); pos = key == null ? ++currentPos : 0; Common.GenericCallHelper <TableStorage <T> >("InstantiateColumnGeneric", type, this, pos, StoragePath, TableName, member.Name, stringLength, maxLength); }
/// <summary> /// 验证输入的最大长度 /// </summary> /// <param name="box">验证框</param> /// <param name="length">最大长度</param> /// <param name="errorMessage">提示信息</param> /// <returns></returns> public static ValidBox MaxLength(this ValidBox box, int length, string errorMessage) { var newBox = new MaxLengthAttribute(length) { ErrorMessage = errorMessage }.ToValidBox(); return(ValidBox.Merge(box, newBox)); }
private void BindInfoProperty(PropertyInfo property) { Type propertyType = property.PropertyType; if (propertyType == typeof(Guid)) { return; } DataMemberAttribute dataMember = property.GetCustomAttributes(typeof(DataMemberAttribute), false) .FirstOrDefault() as DataMemberAttribute; if (dataMember == null) { return; } NotMappedAttribute notMapped = property.GetCustomAttributes(typeof(NotMappedAttribute), false) .FirstOrDefault() as NotMappedAttribute; if (notMapped != null) { return; } DisplayNameAttribute display = property.GetCustomAttributes(typeof(DisplayNameAttribute), false) .FirstOrDefault() as DisplayNameAttribute; MaxLengthAttribute maxLength = property.GetCustomAttributes(typeof(MaxLengthAttribute), false) .FirstOrDefault() as MaxLengthAttribute; if (display == null) { return; } if (propertyType == typeof(string)) { //字符串 TextBox textBox = EditControls.FirstOrDefault(c => c.Name == typeof(TextBox).Name + property.Name) as TextBox; if (textBox != null) { object value = property.GetValue(goodsAdditional, null); textBox.Text = value != null?value.ToString() : ""; } } //日期 else if (propertyType == typeof(DateTime)) { DateTimePicker dateTimePicker = EditControls.FirstOrDefault(c => c.Name == typeof(DateTimePicker).Name + property.Name) as DateTimePicker; if (dateTimePicker != null) { object value = property.GetValue(goodsAdditional, null); DateTime date = DateTime.Parse(value.ToString()).Date; if (date > dateTimePicker.MinDate && date < dateTimePicker.MaxDate) { dateTimePicker.Value = DateTime.Parse(value.ToString()); } } } }
private static Errors ValidateProperty(PropertyInfo property, object entity, object value) { var errors = new Errors(); RequiredAttribute.Validate(property, value, errors); MaxLengthAttribute.Validate(property, value, errors); MinLengthAttribute.Validate(property, value, errors); return(errors); }
public void ValidationAttributeExtensionsResolveErrorMessageExceptionTest() { var attribute = new MaxLengthAttribute(10) { ErrorMessageResourceType = typeof(string), ErrorMessageResourceName = "MaxLengthErrorMessage" }; attribute.ResolveErrorMessage(); }
/// <summary> /// Verify whether value is lessthan or equal special maxlength. /// maxLength must be greater than zero. /// Allow value is null /// </summary> /// <param name="value">Value</param> /// <param name="maxLength">max length,must be greater than zero</param> /// <returns>Return whether the verification has passed</returns> public static bool MaxLength(this object value, int maxLength) { if (maxLength < 1) { throw new ArgumentException($"{nameof(maxLength)} must be greater than zero"); } var maxLengthAttribute = new MaxLengthAttribute(maxLength); return(maxLengthAttribute.IsValid(value)); }
public ListPropertyMaxLengthAttribute(int length, string propertyName, string typeValue = "") { if (string.IsNullOrEmpty(propertyName)) { throw new ArgumentException("propertyName must not be null or empty"); } maxLengthAttribute = new MaxLengthAttribute(length); this.length = length; this.propertyName = propertyName; this.typeValue = typeValue; }
private static void ApplyMaxLengthAttribute(OpenApiSchema schema, MaxLengthAttribute maxLengthAttribute) { if (schema.Type == "array") { schema.MaxItems = maxLengthAttribute.Length; } else { schema.MaxLength = maxLengthAttribute.Length; } }
/// <summary> /// Adds a MaxLengthAttribute. /// </summary> /// <param name="length">The maximum allowable length of array or string data.</param> /// <param name="errMsg">Gets or sets an error message to associate with a validation control if validation fails.</param> /// <returns></returns> public BaValidatorList MaxLength(int length, string errMsg = null) { var att = new MaxLengthAttribute(length); if (errMsg != null) { att.ErrorMessage = errMsg; } Add(att); return(this); }
private int GetMaxLength(PropertyInfo property) { int maxLength = -1; MaxLengthAttribute maxLengthAttribute = property.GetCustomAttribute <MaxLengthAttribute>(); if (maxLengthAttribute != null) { maxLength = maxLengthAttribute.Length; } return(maxLength); }
public void Given_MaxLengthAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(int length) { var name = "hello"; var acceptor = new OpenApiSchemaAcceptor(); var type = new KeyValuePair <string, Type>(name, typeof(decimal)); var attribute = new MaxLengthAttribute(length); this._visitor.Visit(acceptor, type, this._strategy, attribute); acceptor.Schemas.Should().ContainKey(name); acceptor.Schemas[name].Type.Should().Be("number"); acceptor.Schemas[name].MaxLength.Should().Be(length); }
private static int?GetMax(PropertyInfo property) { int?max = null; if (property == null) { return(null); } MaxLengthAttribute attribute = (MaxLengthAttribute)property.GetCustomAttributes(true).FirstOrDefault(a => a.GetType() == typeof(MaxLengthAttribute)); max = attribute?.Length; return(max); }
private static Range GetRange(MinLengthAttribute minLengthAttribute, MaxLengthAttribute maxLengthAttribute) { var min = minLengthAttribute?.Length ?? 0; var max = maxLengthAttribute?.Length ?? int.MaxValue; // To avoid creation of empty strings/arrays. if (max > 0 && min == 0) { min = 1; } return(new Range(min, max)); }
public void AtMaxLength() { var attribute = new MaxLengthAttribute(4); ValidationAssert.IsValid(attribute, this, "FourLetterWord"); }
public void TooLong() { var attribute = new MaxLengthAttribute(3); ValidationAssert.IsNotValid(attribute, this, "FourLetterWord"); }
public void NullIsValid() { var attribute = new MaxLengthAttribute(10); ValidationAssert.IsValid(attribute, this, "NullString"); }