tags:

views:

80

answers:

1

I need to do some validation where 1 of 2 fields must be entered. What is the best was to do this in MVC 2?

The fields are;

<%: Html.EditorFor(model => model.contract.ClientOrderNumber)%>

and

<%: Html.TextAreaFor(model => model.contract.InstructionWithoutClientOrder, 
                        new { maxlength = "255", style = "width:200px;height:100px;"})%>
+2  A: 

You have to add an validation attribute to the CLASS of your model.

[AttributeUsage(AttributeTargets.Class)]
public class SomeValidationAttribute : ValidationAttribute 
{
    public override bool IsValid(object value)
    {
        //value contains your complete model!
        MyViewModel model = (MyViewModel) value;

        return !string.IsNullOrWhiteSpace(model.X) || !string.IsNullOrWhiteSpace(model.Y)
    }
}

And on your viewmodel:

[SomeValidation]
public class MyViewModel
{
    public string X { get; set; }
    public string Y { get; set; }
}
Gidon