views:

18

answers:

1

If I have two validators, a NotNullValidator and a StringLengthValidator, is there a way to get only a Null Validation Error and not both. For example:

public class Test
{
    [NotNullValidator(MessageTemplate="Name is required"),
    StringLengthValidator(1,50, MessageTemplate="Name must be between 1 and 50 characters")]
    public string Name { get; set; }
}

Test test = new Test {Name = null};
ValidationResults r = Validation.Validate(test);
if (!r.IsValid)
{
    foreach (var test in r)
    {
        Console.WriteLine(test.Message);
    }
}

In this case I get both validation errors. I get one telling me that the "Name is required" and another telling me that it should be between 1 and 50 characters. I only want to see that name is required in this case. Is this possible?

A: 

Just remove the NotNullValidatorAttribute and you're good to go.

Steven
@Steven But that doesn't tell me that the value wasn't specified. It tells me that it is the incorrect length. The two are separate issues and I want to handle them separately.
uriDium
@uriDium: When you specify two validation rules (attributes), VAB will always run them both. The behavior you want is "run validator 1, and only when it is valid, run validator 2". This behavior is not supported out of the box. You can write a `[SelfValidation]` method, or a custom `NotNullStringLengthValidator` to get this behavior.
Steven
@Steven - I thought as much :(
uriDium