views:

128

answers:

1

I have a SearchViewModel with these properties:

    [RegularExpression("name")]
    public String SortField;

    [RegularExpression("asc|desc")]
    public String SortDirection;

As you can see, I want "name" to be the only valid value of SortField at this time, and "asc" or "desc" the only valid values for SortDirection.

However, ValidateModel isn't catching any error when the values are different, and ModelState.IsValid returns true. Basically I can supply any value and it will always go through.

The abbreviated controller method:

    public ActionResult List(SearchViewModel model)
    {            
        ValidateModel(model); // No error here
        Boolean isValid = ModelState.IsValid // This is true

        //...
    }

What am I doing wrong?

Edit: I'm not sure if this is important, but I'm using a custom ModelBinder.

+1  A: 

Those aren't properties; they're fields. Binding and validation only work against properties.

FYI - [RegularExpression] also allows the user to specify no value for the input (which gets converted to a null). If you want to disallow null values, use [Required] in addition to [RegularExpression].

Levi
Got it, thank you.
Alex