1

I have a custom validation attribute which isn't triggering. Please refer to the following code for more details.

public HttpResponseMessage GetTestResponse()
        {
            var model = new TestClass1()
            {
                Id = 1,
                address = new Address() { StreetName = "test" }
            };
            bool validateAllProperties = false;

            var results = new List<ValidationResult>();

            bool isValid = Validator.TryValidateObject(
                model,
                new ValidationContext(model, null, null),
                results,
                validateAllProperties);
            if (isValid)
            {
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest);
            }
        }
    public class TestClass1
    {

        public string Name { get; set; }
        [Required,Range(1,5)]
        public int Id { get; set; }
        [Required]
        [ValidateObject("StreetNumber is required")]
        public Address address { get; set; }
    }
    public class Address
    {
        [Required]
        public int? StreetNumber { get; set; }
        public string StreetName { get; set; }

    }
    public class ValidateObjectAttribute : ValidationAttribute
    {
        public ValidateObjectAttribute(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }
        protected override ValidationResult IsValid(object value, 
        ValidationContext validationContext)
        {
            var results = new List<ValidationResult>();
            var context = new ValidationContext(value, null, null);

            Validator.TryValidateObject(value, context, results, true);

            if (results.Count != 0)
            {
                var compositeResults = new CompositeValidationResult(String.Format("Validation for {0} failed!", validationContext.DisplayName));
                results.ForEach(compositeResults.AddResult);

                return compositeResults;
            }

            return ValidationResult.Success;
        }
    }

    public class CompositeValidationResult : ValidationResult
    {
        private readonly List<ValidationResult> _results = new List<ValidationResult>();

        public IEnumerable<ValidationResult> Results
        {
            get
            {
                return _results;
            }
        }

        public CompositeValidationResult(string errorMessage) : base(errorMessage) { }
        public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) { }
        protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) { }

        public void AddResult(ValidationResult validationResult)
        {
            _results.Add(validationResult);
        }
    }

The custom attribute not triggering and the isvalid returning true, which should be false as one of the property inside Address class is required and is not being provided. Is there a a piece missing that I should be adding in order to make this work?

1 Answer 1

1

The example appears to be missing this part:

Make the class not inheritable. Add the NotInheritable keyword in Visual Basic or the sealed keyword in Visual C#.

e.g.:

[AttributeUsage(AttributeTargets.Property | 
  AttributeTargets.Field, AllowMultiple = false)]
sealed public class CustomAttribute : ValidationAttribute
{

}

REF: How to: Customize Data Field Validation in the Data Model Using Custom Attributes

Sign up to request clarification or add additional context in comments.

1 Comment

I added the sealed and AttributeUsage to the CustomAttribute class but it still does not trigger. I am using dot net 4.5 is this even supported? On the reference link I see that Microsoft has a message We're no longer updating this content regularly. Check the Microsoft Product Lifecycle for information about how this product, service, technology, or API is supported.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.