Group validation messages for multiple properties together into one message asp.net mvc

前端 未结 4 1355
失恋的感觉
失恋的感觉 2020-12-10 03:19

I have a view model that has year/month/day properties for someone\'s date of birth. All of these fields are required. Right now, if someone doesn\'t enter anything for the

4条回答
  •  青春惊慌失措
    2020-12-10 03:47

    You could do that simply using CustomAttribute.

    Just put this attribute on your model

    [CustomValidation(typeof(MyModel), "ValidateRelatedObject")]
    

    and then simply define the rules to validate the values in the following method:

    public static ValidationResult ValidateRelatedObject(object value, ValidationContext context)
    {
        var context = new ValidationContext(value, validationContext.ServiceContainer, validationContext.Items);
        var results = new List();
        Validator.TryValidateObject(value, context, results);
    
        // TODO: Wrap or parse multiple ValidationResult's into one ValidationResult
    
        return result; 
    }
    

    For more information, you could visit this link.

提交回复
热议问题