0
votes

I am using .NET 4 MVC 2 in my project. I basically have two classes, which I use for my validation. Class A is my (main) model, class B is an composite attribute which class A may have. The code looks like the following:

[Bind(Exclude = "A_ID")]
    public class A_Validation
    {
        [Required(ErrorMessage = "something is missing")]
        public string title { get; set; }

        // some more attributes ...

        public B b { get; set; }
    }

All my validation based on class A is working very well. But now I want to validate the composite attribute B, which looks like the following.

[Bind(Exclude = "B_ID")]
    public class B_Validation
    {
        [Required(ErrorMessage = "missing")]
        [Range(1, 210, ErrorMessage = "range between 1 and 210")]
        public int first { get; set; }

        [Required(ErrorMessage = "missing")]
        [Range(1, 210, ErrorMessage = "range between 1 and 210")]
        public int second { get; set; }

        [Required(ErrorMessage = "missing")]
        [Range(1, 210, ErrorMessage = "range between 1 and 210")]
        public int third { get; set; }
    }

I am able to check the ranges of B's three attributes first,second and third. What I additionally want is to check if the sum of all three attributes first,second and third is below a certain threshold.

Any ideas how to proceed?

I think ViewModels might help, but i have no experience in using them.

1

1 Answers

0
votes

Have you tried writing a custom validation attribute:

public class SumBelowAttribute : ValidationAttribute
{
    private readonly int _max;
    public SumBelowAttribute(int max)
    {
        _max = max;
    }

    public override bool IsValid(object value)
    {
        var b = value as B_Validation;
        if (b != null)
        {
            return b.first + b.second + b.third < _max;
        }
        return base.IsValid(value);
    }
}

and then decorate the B property with this attribute:

[SumBelow(123)]
public B b { get; set; }