Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify error member key in ASP.NET MVC CustomValidation?

I'm trying to add CustomValidation and make it return error for

Html.ValidationMessageFor(m => m.SubleaseCompany)

[CustomValidation(typeof(CreateSpaceModelValidation), "ValidateCreateSpaceModel")]
public class CreateSpaceModel
{
    public Building Building { get; set; }
    public Space Space { get; set; }

    public string SubleaseCompany { get; set; }
}

public class CreateSpaceModelValidation
{
    public static ValidationResult ValidateCreateSpaceModel(CreateSpaceModel model)
    {
        return new ValidationResult("You should specify Sublease Contact", new[] { "SubleaseCompany" }).;
    }
}

I'm using second argument for ValidationResult constructor (memberNames) but this doesn't seem to work.

like image 253
Evgenyt Avatar asked Aug 02 '10 16:08

Evgenyt


People also ask

What does ModelState IsValid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.

What is the use of ModelState in MVC?

The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.

What is ModelState?

The ModelState represents a collection of name and value pairs that were submitted to the server during a POST. It also contains a collection of error messages for each value submitted. Despite its name, it doesn't actually know anything about any model classes, it only has names, values, and errors.


1 Answers

Looks like the MVC team never implemented the functionality for the MemberNames parameter. See the following exert from.... http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

In some situations, you might be tempted to use the second constructor overload of ValidationResult that takes in an IEnumerable of member names. For example, you may decide that you want to display the error message on both fields being compared, so you change the code to this:

return new ValidationResult(
    FormatErrorMessage(validationContext.DisplayName),

new[] { validationContext.MemberName, OtherProperty });

If you run your code, you will find absolutely no difference. This is because although this overload is present and presumably used elsewhere in the .NET framework, the MVC framework completely ignores ValidationResult.MemberNames.

like image 82
tkerwood Avatar answered Oct 19 '22 23:10

tkerwood