public override IEnumerable <ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) { var allValidators = base.GetValidators(metadata, context); var validators = new List <ModelValidator>(); foreach (var v in allValidators) { if (v.GetType().Name == "NumericModelValidator") { NumericAttribute attribute = new NumericAttribute { ErrorMessage = Resources.FieldMustBeNumeric }; DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute); validators.Add(validator); } else if (v.GetType().Name == "DateModelValidator") { DateAttribute attribute = new DateAttribute { ErrorMessage = Resources.FieldMustBeDate }; DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute); validators.Add(validator); } else { validators.Add(v); } } return(validators); }
public void ValidateDate(int days, Temporality temporality, bool expected) { var attribute = new DateAttribute(temporality); var actual = attribute.IsValid(DateTime.Now.AddDays(days)); Assert.AreEqual(expected, actual); }
public void Test_DateAttribute([ValueSource(nameof(Comparisons))] ValidationComparison comparison, [ValueSource(nameof(Dates))] DateTime date) { var attribute = new DateAttribute(comparison); var result = attribute.IsValid(date); Assert.IsTrue(result); }
//模型级错误的验证方式。 //只有不存在属性级错误的时候会调用;如果有属性级错误不会调用 public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var holiday = DateAttribute.FromDateString(this.Day).Value; if (T_Holiday.Count(Where.Eq(nameof(T_Holiday.Holiday), holiday)) > 0) { yield return(new ValidationResult("该日期已存在。不可加入重复的假期。", new string[] { nameof(Day) })); } }
public void ErrorMessageTest() { var attribute = new DateAttribute(); attribute.ErrorMessage = "SampleErrorMessage"; const int invalidValue = 0; var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null)); Assert.AreEqual("SampleErrorMessage", result.ErrorMessage); }
public void ErrorResourcesTest() { var attribute = new DateAttribute(); attribute.ErrorMessageResourceName = "ErrorMessage"; attribute.ErrorMessageResourceType = typeof(ErrorResources); const int invalidValue = 0; var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null)); Assert.AreEqual(ErrorResources.ErrorMessage, result.ErrorMessage); }
//模型级错误的验证方式。 public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { //逻辑与新规时不太相同 var holiday = DateAttribute.FromDateString(this.Day).Value; var count = T_Holiday.Count(Where.And( Where.Eq(nameof(T_Holiday.Holiday), holiday), Where.NotEq(nameof(T_Holiday.Id), this.Id) )); if (count > 0) { yield return(new ValidationResult("该日期已存在。不可加入重复的假期。", new string[] { nameof(Day) })); } }
public void IsValidTests() { var attribute = new DateAttribute(); Assert.IsTrue(attribute.IsValid(null)); // Don't check for required Assert.IsTrue(attribute.IsValid(DateTime.Now)); Assert.IsTrue(attribute.IsValid(DateTime.Now.ToShortDateString())); Assert.IsTrue(attribute.IsValid("12/31/2010")); Assert.IsFalse(attribute.IsValid(12)); Assert.IsFalse(attribute.IsValid("12.90")); Assert.IsFalse(attribute.IsValid("February 24th")); Assert.IsFalse(attribute.IsValid("yesterday")); Assert.IsFalse(attribute.IsValid("80/80/2011")); }
public IActionResult Create(HolidayVo vo) { if (!ModelState.IsValid) { return(View("Index", vo)); } var record = new T_Holiday { Holiday = DateAttribute.FromDateString(vo.Day).Value, Holiday_Name = vo.Name }; record.Insert(); return(View(record)); }
public void GlobalizedErrorResourcesTest() { System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX"); var attribute = new DateAttribute(); attribute.ErrorMessageResourceName = "ErrorMessage"; attribute.ErrorMessageResourceType = typeof(ErrorResources); const int invalidValue = 0; var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null)); Assert.AreEqual("mensaje de error", result.ErrorMessage); }
public IActionResult Update(HolidayVo vo) { if (!ModelState.IsValid) { return(View("Edit", vo)); } var record = new T_Holiday { Id = vo.Id, Holiday = DateAttribute.FromDateString(vo.Day).Value, Holiday_Name = vo.Name }; record.Update(); return(View(vo)); }
public void IsValidTests() { var attribute = new DateAttribute(); System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us"); Assert.IsTrue(attribute.IsValid(null)); // Don't check for required Assert.IsTrue(attribute.IsValid(DateTime.Now)); Assert.IsTrue(attribute.IsValid(DateTime.Now.ToShortDateString())); Assert.IsTrue(attribute.IsValid("12/31/2010")); Assert.IsFalse(attribute.IsValid(12)); Assert.IsFalse(attribute.IsValid("12.90")); Assert.IsFalse(attribute.IsValid("February 24th")); Assert.IsFalse(attribute.IsValid("yesterday")); Assert.IsFalse(attribute.IsValid("80/80/2011")); }
private static string WriteExtenders(PropertyInfo p, out bool isValidatable) { isValidatable = false; StringBuilder sb = new StringBuilder(); sb.Append(".extend({ editState : false, disableValidation : false, empty : true })"); RequiredAttribute requiredAttribute = p.GetCustomAttribute <RequiredAttribute>(); if (requiredAttribute != null) { sb.Append($".extend({{ required: {{ message: \"{requiredAttribute.FormatErrorMessage(p.Name)}\", onlyIf: function() {{ return ko.utils.isPropertyValidatable(self, \"{ p.Name}\"); }} }} }})"); isValidatable = true; } MinLengthAttribute minLengthAttribute = p.GetCustomAttribute <MinLengthAttribute>(); if (minLengthAttribute != null) { sb.Append(string.Format(".extend({ minLength: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", minLengthAttribute.FormatErrorMessage(p.Name), minLengthAttribute.Length, p.Name)); isValidatable = true; } MaxLengthAttribute maxLengthAttribute = p.GetCustomAttribute <MaxLengthAttribute>(); if (maxLengthAttribute != null) { sb.Append(string.Format(".extend({ maxLength: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", maxLengthAttribute.FormatErrorMessage(p.Name), maxLengthAttribute.Length, p.Name)); isValidatable = true; } RegularExpressionAttribute regularExpressionAttribute = p.GetCustomAttribute <RegularExpressionAttribute>(); if (regularExpressionAttribute != null) { sb.Append(string.Format(".extend({ pattern: { message: \"{0}\", params: /{1}/, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", regularExpressionAttribute.FormatErrorMessage(p.Name), regularExpressionAttribute.Pattern, p.Name)); isValidatable = true; } UrlAttribute urlAttribute = p.GetCustomAttribute <UrlAttribute>(); if (urlAttribute != null) { sb.Append(string.Format(".extend({ pattern: { message: \"{0}\", params: /{1}/, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", urlAttribute.FormatErrorMessage(p.Name), urlAttribute, p.Name)); isValidatable = true; } DateAttribute dateAttribute = p.GetCustomAttribute <DateAttribute>(); if (dateAttribute != null) { sb.Append(string.Format(".extend({ date: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })", dateAttribute.FormatErrorMessage(p.Name), p.Name)); isValidatable = true; } NumericAttribute numericAttribute = p.GetCustomAttribute <NumericAttribute>(); if (numericAttribute != null) { sb.Append( string.Format(".extend({ number: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } }).extend({ numeric: {2} })", numericAttribute.FormatErrorMessage(p.Name), p.Name, numericAttribute.Precision)); isValidatable = true; } EmailAttribute emailAttribute = p.GetCustomAttribute <EmailAttribute>(); if (emailAttribute != null) { sb.Append(string.Format(".extend({ email: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } })", emailAttribute.FormatErrorMessage(p.Name), p.Name)); isValidatable = true; } DigitsAttribute digitsAttribute = p.GetCustomAttribute <DigitsAttribute>(); if (digitsAttribute != null) { sb.Append(string.Format(".extend({ digit: { message: \"{0}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{1}\"); } } }).extend({ numeric: 0 })", digitsAttribute.FormatErrorMessage(p.Name), p.Name)); isValidatable = true; } MinAttribute minAttribute = p.GetCustomAttribute <MinAttribute>(); if (minAttribute != null) { sb.Append(string.Format(".extend({ min: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", minAttribute.FormatErrorMessage(p.Name), minAttribute.Min, p.Name)); isValidatable = true; } MaxAttribute maxAttribute = p.GetCustomAttribute <MaxAttribute>(); if (maxAttribute != null) { sb.Append(string.Format(".extend({ max: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", maxAttribute.FormatErrorMessage(p.Name), maxAttribute.Max, p.Name)); isValidatable = true; } EqualToAttribute equalToAttribute = p.GetCustomAttribute <EqualToAttribute>(); if (equalToAttribute != null) { sb.Append(string.Format(".extend({ equal: { message: \"{0}\", params: {1}, onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", equalToAttribute.FormatErrorMessage(p.Name), equalToAttribute.OtherProperty, p.Name)); isValidatable = true; } CompareAttribute compareAttribute = p.GetCustomAttribute <CompareAttribute>(); if (compareAttribute != null) { sb.Append(string.Format(".extend({ equal: { message: \"{0}\", params: \"{1}\", onlyIf: function() { return ko.utils.isPropertyValidatable(self, \"{2}\"); } } })", compareAttribute.FormatErrorMessage(p.Name), compareAttribute.OtherProperty, p.Name)); isValidatable = true; } FormatterAttribute formatterAttribute = p.GetCustomAttribute <FormatterAttribute>(); if (formatterAttribute != null) { sb.Append(string.Format(".formatted({0}, {1})", formatterAttribute.Formatter, JsonConvert.SerializeObject(formatterAttribute.Arguments))); } return(sb.ToString()); }
public static KeyValuePair <string, List <ProductValue> > CreateValue(this DateAttribute attribute, DateTime data, string locale = null, string scope = null) { return(attribute.CreateValue((object)data, locale, scope)); }
public void testAddBooking() { var range = new System.ComponentModel.DataAnnotations.RangeAttribute(0, 100); var dateValidation = new DateAttribute(); // Alle Attribute richtig Booking b1 = new Booking { currentCharge = 30, requiredDistance = 150, connectorType = ConnectorType.CCSCombo2Plug, start = new DateTime(2020, 7, 8, 8, 0, 0), end = new DateTime(2020, 7, 8, 10, 0, 0) }; Assert.IsTrue(range.IsValid(b1.currentCharge)); Assert.IsTrue(b1.requiredDistance > 0 && b1.requiredDistance <= 1000); Assert.IsTrue(dateValidation.IsValid(b1.start)); Assert.IsTrue(dateValidation.IsValid(b1.end)); Assert.IsTrue(b1.end > b1.start); // currentCharge ungültig Booking b2 = new Booking { currentCharge = -30, requiredDistance = 150, connectorType = ConnectorType.CCSCombo2Plug, start = new DateTime(2020, 7, 8, 8, 0, 0), end = new DateTime(2020, 7, 8, 10, 0, 0) }; Assert.IsFalse(range.IsValid(b2.currentCharge)); Assert.IsTrue(b2.requiredDistance > 0 && b2.requiredDistance <= 1000); Assert.IsTrue(dateValidation.IsValid(b2.start)); Assert.IsTrue(dateValidation.IsValid(b2.end)); Assert.IsTrue(b2.end > b2.start); // requiredDistance ungültig Booking b3 = new Booking { currentCharge = 30, requiredDistance = -150, connectorType = ConnectorType.CCSCombo2Plug, start = new DateTime(2020, 7, 8, 8, 0, 0), end = new DateTime(2020, 7, 8, 10, 0, 0) }; Assert.IsTrue(range.IsValid(b3.currentCharge)); Assert.IsFalse(b3.requiredDistance > 0 && b3.requiredDistance <= 1000); Assert.IsTrue(dateValidation.IsValid(b3.start)); Assert.IsTrue(dateValidation.IsValid(b3.end)); Assert.IsTrue(b3.end > b3.start); // start ungültig Booking b4 = new Booking { currentCharge = 30, requiredDistance = 150, connectorType = ConnectorType.CCSCombo2Plug, start = new DateTime(2020, 5, 5, 8, 0, 0), end = new DateTime(2020, 7, 8, 10, 0, 0) }; Assert.IsTrue(range.IsValid(b4.currentCharge)); Assert.IsTrue(b4.requiredDistance > 0 && b4.requiredDistance <= 1000); Assert.IsFalse(dateValidation.IsValid(b4.start)); Assert.IsTrue(dateValidation.IsValid(b4.end)); Assert.IsTrue(b4.end > b4.start); // end ungültig Booking b5 = new Booking { currentCharge = 30, requiredDistance = 150, connectorType = ConnectorType.CCSCombo2Plug, start = new DateTime(2020, 7, 8, 8, 0, 0), end = new DateTime(2020, 7, 7, 10, 0, 0) }; Assert.IsTrue(range.IsValid(b5.currentCharge)); Assert.IsTrue(b5.requiredDistance > 0 && b3.requiredDistance <= 1000); Assert.IsTrue(dateValidation.IsValid(b5.start)); Assert.IsTrue(dateValidation.IsValid(b5.end)); Assert.IsFalse(b5.end > b5.start); }
/// <summary> /// Génère l'attribut de validation issu du domaine. /// </summary> /// <param name="validationAttribute">Attribut de validation.</param> /// <returns>Attribut de validation formatté.</returns> protected override string LoadValidationAttribute(ValidationAttribute validationAttribute) { if (validationAttribute == null) { throw new ArgumentNullException("validationAttribute"); } RangeAttribute rangeAttr = validationAttribute as RangeAttribute; if (rangeAttr != null) { return("[Range(" + rangeAttr.Minimum.ToString() + ", " + rangeAttr.Maximum.ToString() + ")]"); } EmailAttribute emailAttr = validationAttribute as EmailAttribute; if (emailAttr != null) { return("[Email(" + emailAttr.MaximumLength + ")]"); } StringLengthAttribute strLenAttr = validationAttribute as StringLengthAttribute; if (strLenAttr != null) { StringBuilder sb = new StringBuilder("[StringLength("); sb.Append(strLenAttr.MaximumLength); if (strLenAttr.MinimumLength > 0) { sb.Append(" , "); sb.Append("MinimumLength = "); sb.Append(strLenAttr.MinimumLength); } sb.Append(")]"); return(sb.ToString()); } RegularExpressionAttribute regexAttr = validationAttribute as RegularExpressionAttribute; if (regexAttr != null) { return("[RegularExpression(\"" + regexAttr.Pattern + "\")]"); } DateAttribute dateAttr = validationAttribute as DateAttribute; if (dateAttr != null) { return(string.Format(CultureInfo.InvariantCulture, "[Date({0})]", dateAttr.Precision)); } NumeroSiretAttribute siretAttr = validationAttribute as NumeroSiretAttribute; if (siretAttr != null) { return("[NumeroSiret]"); } throw new NotSupportedException("Recopie d'attribut de validation par aspect non géré pour : " + validationAttribute.GetType().ToString()); }