FormatErrorMessage() public method

Applies formatting to an error message, based on the data field where the error occurred.
public FormatErrorMessage ( string name ) : string
name string The name to include in the formatted message.
return string
Esempio n. 1
0
        /// <summary>
        /// Valide les contraintes pour une propriété.
        /// </summary>
        /// <param name="value">Valeur de la propriété.</param>
        /// <param name="checkNullValue">True si la nullité doit être vérifiée.</param>
        /// <param name="isForceRequirement">Si on force le fait que la propriété est requise ou non.</param>
        internal void ValidConstraints(object value, bool checkNullValue, bool?isForceRequirement)
        {
            bool isRequired = this.IsRequired;

            if (isForceRequirement.HasValue)
            {
                isRequired = isForceRequirement.Value;
            }

            if (isRequired && checkNullValue)
            {
                RequiredAttribute c = new RequiredAttribute {
                    AllowEmptyStrings = false, ErrorMessageResourceType = typeof(SR), ErrorMessageResourceName = "ConstraintNotNull"
                };
                ExtendedValue extVal = value as ExtendedValue;
                if (extVal != null)
                {
                    if (!c.IsValid(extVal.Value) || !c.IsValid(extVal.Metadata))
                    {
                        throw new ConstraintException(this, c.FormatErrorMessage(PropertyName));
                    }
                }
                else if (!c.IsValid(value))
                {
                    throw new ConstraintException(this, c.FormatErrorMessage(PropertyName));
                }
            }

            this.Domain.CheckValue(value, this);
        }
        /// <summary>
        /// Determines whether the specified object is valid.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        /// <returns>A collection that holds failed-validation information.</returns>
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var required = new RequiredAttribute();

            switch (Kind)
            {
            case CredentialsKind.Default:
                break;

            case CredentialsKind.Environment:
                if (string.IsNullOrEmpty(Environment) == true)
                {
                    yield return(new ValidationResult(required.FormatErrorMessage(nameof(Environment))));
                }
                break;

            case CredentialsKind.Impersonate:
                if (string.IsNullOrEmpty(Environment) == true)
                {
                    yield return(new ValidationResult(required.FormatErrorMessage(nameof(Environment))));
                }
                if (ImpersonateUserId.HasValue == false)
                {
                    yield return(new ValidationResult(required.FormatErrorMessage(nameof(ImpersonateUserId))));
                }
                break;

            default:
                throw new InvalidOperationException("Unsupported value: " + Kind);
            }
        }
Esempio n. 3
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectInstance.GetType().GetProperty(PropertyName);

            if (property != null)
            {
                var  propertyValue        = property.GetValue(validationContext.ObjectInstance, null);
                bool isConditionTypeValid = false;
                switch (ConditionType)
                {
                case ConditionType.IsEqualTo:
                    if (propertyValue.IsNotNull())
                    {
                        isConditionTypeValid = propertyValue.Equals(ConditionValue);
                    }
                    else if (propertyValue.IsNull() && ConditionValue.IsNull())
                    {
                        isConditionTypeValid = true;
                    }
                    else if (propertyValue.IsNull() && ConditionValue.IsNotNull())
                    {
                        isConditionTypeValid = false;
                    }
                    break;

                case ConditionType.IsNotEqualTo:
                    if (propertyValue.IsNotNull())
                    {
                        isConditionTypeValid = !propertyValue.Equals(ConditionValue);
                    }
                    else if (propertyValue.IsNull() && ConditionValue.IsNull())
                    {
                        isConditionTypeValid = false;
                    }
                    else if (propertyValue.IsNull() && ConditionValue.IsNotNull())
                    {
                        isConditionTypeValid = true;
                    }
                    break;
                }
                if (isConditionTypeValid)
                {
                    if (!requiredAttribute.IsValid(value))
                    {
                        return(new ValidationResult(requiredAttribute.FormatErrorMessage(validationContext.DisplayName)));
                    }
                }
            }
            return(ValidationResult.Success);
        }
        private void SetUpRequiredFieldValidator(RequiredFieldValidator validator, MetaColumn column)
        {
            var requiredAttribute = column.Metadata.RequiredAttribute;

            if (requiredAttribute != null && requiredAttribute.AllowEmptyStrings)
            {
                // Dev10



                IgnoreModelValidationAttribute(typeof(RequiredAttribute));
            }
            else if (column.IsRequired)
            {
                validator.Enabled = true;

                // Make sure the attribute doesn't get validated a second time by the DynamicValidator
                IgnoreModelValidationAttribute(typeof(RequiredAttribute));

                if (String.IsNullOrEmpty(validator.ErrorMessage))
                {
                    string columnErrorMessage = column.RequiredErrorMessage;
                    if (String.IsNullOrEmpty(columnErrorMessage))
                    {
                        // generate default error message
                        validator.ErrorMessage = HttpUtility.HtmlEncode(s_defaultRequiredAttribute.FormatErrorMessage(column.DisplayName));
                    }
                    else
                    {
                        validator.ErrorMessage = HttpUtility.HtmlEncode(columnErrorMessage);
                    }
                }
            }
        }
Esempio n. 5
0
        private void SetUpRequiredFieldValidator(RequiredFieldValidator validator, MetaColumn column)
        {
            var requiredAttribute = column.Metadata.RequiredAttribute;

            if (requiredAttribute != null && requiredAttribute.AllowEmptyStrings)
            {
                // Dev10 Bug 749744
                // If somone explicitly set AllowEmptyStrings = true then we assume that they want to
                // allow empty strings to go into a database even if the column is marked as required.
                // Since ASP.NET validators always get an empty string, this essential turns of
                // required field validation.
                IgnoreModelValidationAttribute(typeof(RequiredAttribute));
            }
            else if (column.IsRequired)
            {
                validator.Enabled = true;

                // Make sure the attribute doesn't get validated a second time by the DynamicValidator
                IgnoreModelValidationAttribute(typeof(RequiredAttribute));

                if (String.IsNullOrEmpty(validator.ErrorMessage))
                {
                    string columnErrorMessage = column.RequiredErrorMessage;
                    if (String.IsNullOrEmpty(columnErrorMessage))
                    {
                        // generate default error message
                        validator.ErrorMessage = HttpUtility.HtmlEncode(s_defaultRequiredAttribute.FormatErrorMessage(column.DisplayName));
                    }
                    else
                    {
                        validator.ErrorMessage = HttpUtility.HtmlEncode(columnErrorMessage);
                    }
                }
            }
        }
        public void Entity_EndEditValidatesRequiredProperties()
        {
            // Start with an entity that doesn't have its required properties
            // satisfied (Name is required)
            Cities.City     city         = new Cities.City();
            IEditableObject editableCity = (IEditableObject)city;

            RequiredAttribute template           = new RequiredAttribute();
            string            expectedMemberName = "CityName";
            string            expectedError      = template.FormatErrorMessage(expectedMemberName);

            // Begin the edit transaction
            editableCity.BeginEdit();

#if SILVERLIGHT
            string expectedMember = "Name";

            // End the edit transaction, which performs property and entity-level validation
            editableCity.EndEdit();
            Assert.AreEqual <int>(1, city.ValidationErrors.Count, "After EndEdit");
            Assert.AreEqual <int>(1, city.ValidationErrors.Single().MemberNames.Count(), "MemberNames count after EndEdit");
            Assert.AreEqual <string>(expectedMember, city.ValidationErrors.Single().MemberNames.Single(), "Member name after EndEdit");
            Assert.AreEqual <string>(expectedError, city.ValidationErrors.Single().ErrorMessage, "ErrorMessage after EndEdit");
#else
            ExceptionHelper.ExpectException <ValidationException>(delegate
            {
                ((IEditableObject)city).EndEdit();
            }, expectedError);
#endif
        }
Esempio n. 7
0
 public override string FormatErrorMessage(string name)
 {
     if (!String.IsNullOrEmpty(this.ErrorMessageString))
     {
         _innerAttribute.ErrorMessage = this.ErrorMessageString;
     }
     return(_innerAttribute.FormatErrorMessage(name));
 }
Esempio n. 8
0
 public override string FormatErrorMessage(string name)
 {
     if (!String.IsNullOrEmpty(this.ErrorMessageString))
     {
         return(String.Format(this.ErrorMessageString, name, ButtonName));
     }
     return(_innerAttribute.FormatErrorMessage(name));
 }
Esempio n. 9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public override string FormatErrorMessage(string name)
 {
     if (!String.IsNullOrEmpty(this.ErrorMessageString))
     {
         required.ErrorMessage = this.ErrorMessageString;
     }
     return(required.FormatErrorMessage(name));
 }
Esempio n. 10
0
        public void RequiredOption_ErrorMessage(string template, string valueName)
        {
            var required = new RequiredAttribute();
            var expected = required.FormatErrorMessage(valueName);
            var app      = new CommandLineApplication();

            app.Option(template, string.Empty, CommandOptionType.SingleValue).IsRequired();
            var validation = app.GetValidationResult();

            Assert.Equal(expected, validation.ErrorMessage);
        }
Esempio n. 11
0
        public void RequiredArgument_ErrorMessage()
        {
            var required = new RequiredAttribute();
            var expected = required.FormatErrorMessage("Arg");
            var app      = new CommandLineApplication();

            app.Argument("Arg", string.Empty).IsRequired();
            var validation = app.GetValidationResult();

            Assert.Equal(expected, validation.ErrorMessage);
        }
Esempio n. 12
0
        public void ValuesSet()
        {
            // Arrange
            ModelMetadata metadata  = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), "Length");
            var           attribute = new RequiredAttribute();

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

            // Assert
            Assert.Same(attribute, validator.Attribute);
            Assert.Equal(attribute.FormatErrorMessage("Length"), validator.ErrorMessage);
        }
        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.Same(attribute, validator.Attribute);
            Assert.Equal(attribute.FormatErrorMessage("Length"), validator.ErrorMessage);
        }
        /// <summary>
        /// Main process of model binding
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object result = null;

            //handle pemisah angka desimal dan ribuan untuk bilangan
            if (bindingContext.ModelType == typeof(double) ||
                bindingContext.ModelType == typeof(double?) ||
                bindingContext.ModelType == typeof(decimal) ||
                bindingContext.ModelType == typeof(decimal?))
            {
                string modelName      = bindingContext.ModelName;
                var    valueResult    = bindingContext.ValueProvider.GetValue(modelName);
                string attemptedValue = valueResult.AttemptedValue;
                bindingContext.ModelState.SetModelValue(modelName, valueResult);
                // Depending on cultureinfo the NumberDecimalSeparator can be "," or "."
                // Both "." and "," should be accepted, but aren't.
                string wantedSeperator    = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
                string alternateSeperator = (wantedSeperator == "," ? "." : ",");
                // ReSharper disable StringIndexOfIsCultureSpecific.1
                if (attemptedValue.IndexOf(wantedSeperator) == -1 &&
                    attemptedValue.IndexOf(alternateSeperator) != -1)
                {
                    attemptedValue = attemptedValue.Replace(alternateSeperator, wantedSeperator);
                }
                try
                {
                    if (bindingContext.ModelType == typeof(Double) || bindingContext.ModelType == typeof(double?))
                    {
                        result = double.Parse(attemptedValue, NumberStyles.Any);
                    }
                    if (bindingContext.ModelType == typeof(Decimal) || bindingContext.ModelType == typeof(decimal?))
                    {
                        result = decimal.Parse(attemptedValue, NumberStyles.Any);
                    }
                }
                catch (FormatException)
                {
                    var requiredAttribute = new RequiredAttribute();
                    //anggap bukan error jika model adalah nullable
                    if (string.IsNullOrEmpty(attemptedValue) &&
                        bindingContext.ModelType != typeof(decimal?) &&
                        bindingContext.ModelType != typeof(double?))
                    {
                        bindingContext.ModelState.AddModelError(modelName, requiredAttribute.FormatErrorMessage(bindingContext.ModelMetadata.DisplayName));
                    }
                }
            }
            return(result);
        }
Esempio n. 15
0
        /// <summary>
        /// Checks whether the value is null or not.
        /// </summary>
        /// <param name="variable">The variable in context.</param>
        /// <param name="getVariableName">The name of the variable that should be populated in the error context.</param>
        /// <param name="actionContext">Current action context.</param>
        /// <param name="modelState">Current model object.</param>
        /// <returns>The status of the operation.</returns>
        public static bool Required(string variable, Expression <Func <string, string> > getVariableName, HttpActionContext actionContext, ModelStateDictionary modelState)
        {
            var variableName = ((MemberExpression)getVariableName.Body).Member.Name;
            var attr         = new RequiredAttribute();

            if (!attr.IsValid(variable) || variable.Equals("null", StringComparison.OrdinalIgnoreCase))
            {
                modelState.AddModelError(attr.ToString(), attr.FormatErrorMessage(variableName));

                AddErrorToResponse(actionContext, modelState);
                return(false);
            }

            return(true);
        }
Esempio n. 16
0
        public async Task BindModelAsync_EnforcesTopLevelRequiredAndLogsSuccessfully_WithEmptyPrefix(
            RequiredAttribute attribute,
            ParameterDescriptor parameterDescriptor,
            ModelMetadata metadata)
        {
            // Arrange
            var expectedKey       = string.Empty;
            var expectedFieldName = metadata.Name ?? nameof(Person);

            var actionContext = GetControllerContext();
            var validator     = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute,
                stringLocalizer: null);

            var sink               = new TestSink();
            var loggerFactory      = new TestLoggerFactory(sink, enabled: true);
            var parameterBinder    = CreateParameterBinder(metadata, validator, loggerFactory: loggerFactory);
            var modelBindingResult = ModelBindingResult.Success(null);

            // Act
            var result = await parameterBinder.BindModelAsync(
                actionContext,
                CreateMockModelBinder(modelBindingResult),
                CreateMockValueProvider(),
                parameterDescriptor,
                metadata,
                "ignoredvalue");

            // Assert
            Assert.False(actionContext.ModelState.IsValid);
            var modelState = Assert.Single(actionContext.ModelState);

            Assert.Equal(expectedKey, modelState.Key);
            var error = Assert.Single(modelState.Value.Errors);

            Assert.Equal(attribute.FormatErrorMessage(expectedFieldName), error.ErrorMessage);
            Assert.Equal(4, sink.Writes.Count());
        }
        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 string GetRequiredErrorMessage(string field)
        {
            var attr = new RequiredAttribute();

            return(attr.FormatErrorMessage(field));
        }
Esempio n. 19
0
 /// <summary>
 /// Applies formatting to an error message, based on the data field where the error occurred.
 /// </summary>
 /// <param name="name">The name of the validated property.</param>
 public override string FormatErrorMessage(string name)
 {
     EnsureErrorMessage();
     UpdateInnerValidator();
     return(reqValidator.FormatErrorMessage(name));
 }
Esempio n. 20
0
        public void DefaultErrorMessage()
        {
            RequiredAttribute required = new RequiredAttribute();

            Assert.AreEqual(String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.RequiredAttribute_ValidationError, "SOME_NAME"), required.FormatErrorMessage("SOME_NAME"));
        }
 public void DefaultErrorMessage() {
     RequiredAttribute required = new RequiredAttribute();
     Assert.AreEqual(String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.RequiredAttribute_ValidationError, "SOME_NAME"), required.FormatErrorMessage("SOME_NAME"));
 }