开发者

Is it possible to use 2 remote validation attributes on a single property?

开发者 https://www.devze.com 2023-03-29 14:22 出处:网络
Is it possible to use 2 remote validation attributes on a single property in a view model? What I would like to be able to do is perform 2 checks, first that a given user id exists in the 开发者_Stac

Is it possible to use 2 remote validation attributes on a single property in a view model?

What I would like to be able to do is perform 2 checks, first that a given user id exists in the 开发者_StackOverflowDB and second that the user has not already set up an account on the system.

I guess I could always make a custom attribute which has both tests in it, but if possible I would prefer to just use the out of the box functionality and chain the validations together.

I cant really combine the logic together into a single JsonResult, as I need to have different error messages depending on how the validation fails, and AFAIK its not possible to return the error message with the validation result?


Actually, you can return a distinctive error message using MVC3 remote validation. See, for example, http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx or http://deanhume.com/Home/BlogPost/mvc-3-and-remote-validation/51.


I'm not sure what you're expecting in terms of "out of the box functionality," but you can create two attributes simple enough. In MVC 3, you also have the opportunity to derive your model from IValidatableObject and implement the Validate method. The latter provides you the ability to perform multiple validations on multiple properties within the context of one another if you find the need.

Here's how you could implement the ValidationAttribute and decorate your property. You'll need two of these, so I'll name this one UsernameExistsAttribute and we'll pretend you created another one called AccountAlreadySetupAttribute overriding the same IdValid method.

public class UsernameExistsAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if((string)value == "Bob")
            return false;
        else
            return true;
    }
}

And in your view model, you decorate the attribute like this:

public class FreakinSweetViewModel
{
    [UsernameExists(ErrorMessage="Username exists")]
    [AccountAlreadySetup(ErrorMessage="Account is not setup")]
    public string Username { get; set; }
}

This will wire up your client and server side validation out of the MVC 3 box.

0

精彩评论

暂无评论...
验证码 换一张
取 消