views:

321

answers:

0

I have an entity model User and it's metadata is

public class UserMetadata
{
    [Required]
    [RegularExpression("...")]
    public String Username { get; set; }

    [Required]
    public String Password { get; set; }
}

I have a controller that recives REST callbacks. One of it's actions is

// POST /users

[HttpPost]
[ActionName("Index")]
public ActionResult Post([Bind(Exclude = "Id")]User NewUser)
{
    return Json(new { ModelState.IsValid, NewUser });
}

and it recives a POST request using jQuery

$.ajax({
    type: 'POST',
    url: 'users',
    data: { 
        username: '',
        password: ''
    }
});

It works fine when I POST back all the User model properties (username, password, [excluding id]), the ModelState.IsValid is true if the username and password is valid and false otherwise.

data: {username: 'user1', password: 'pass'}

If I POST incomplete user model properties (password only, without username)

data: {password: 'pass'}

the Model.IsValid is always true, even if the username is missing from the POST.

I would also like to state that this is a known "issue"/"bug"/feature (as it was called by the users that stumbled upon it) by the MVC 2 team. It was "documented" in this issue thread

The facts are that

There are several reasons we can't run these validations if a value isn't posted back to the server. One of those reasons is that it's perfectly valid to post partial models back to the server. For example, if you're creating a new Customer object and it has a CustomerId property, there won't be a CustomerId posted back to the server, but this shouldn't be an error.

And this is my case

This is just one example of where partial model updates are valid. We're looking into other options, like [IAmRequiredToBePostedBack] that can be applied to individual properties that will cause a binding error if no value is submitted, but so far there is no workable solution and we've not made any decisions.

I would like to know how/if I can force the validation even if the POST data is incomplete. And to get a ModelState.IsValid = false if a property is missing.

If this can't be done, what other validation methods do you recommend (Best practices) ?

I really wouldn't like to have to do it like this

[HttpPost]
[ActionName("Index")]
public ActionResult Post(FormCollection Data)
{
    // Verify the posted data {username, password}
    // and than create the user

    return Json(new { ModelState.IsValid, NewUser });
}

// Or to place my validation logic inside the controller action.