L-Four
L-Four

Reputation: 13541

How to return validation results?

I have an ASP.NET MVC site, that uses a CommandService. This command service is responsible for executing the commands, but before they are executed each command needs to be validated, so there's a Validate operation that returns a ValidationResult, that looks like (simplified):

public class ValidationResult
{
  public List<string> ErrorCodes { get; set; }
}

I would like to improve this, because currently a list of strings is returned, like 'UserDoesNotExist' or 'TitleIsMandatory', and this is not the best approach of course.

It would be better to return something strongly typed. But how can I do that?

Option 1: use one big enum like:

public enum ErrorCode { UserDoesNotExist, TitleIsMandatory}

public class ValidationResult
{
  public List<ErrorCode> ErrorCodes { get; set; }
}

I don't know if it's a good idea to create such a big enum and put all domain error codes in it?

Option 2: use classes

public class ErrorCode {}
public class UserDoesNotExist : ErrorCode {}
public class TitleIsMandatory : ErrorCode {}

public class ValidationResult
{
  public List<ErrorCode> ErrorCodes { get; set; }
}

Is cleaner, but harder to use?

What would you do, or did I miss other options?

Upvotes: 4

Views: 17188

Answers (4)

Yves Reynhout
Yves Reynhout

Reputation: 2990

Maybe a stupid observation, but why not do the validation client-side? Well-behaved clients should validate commands before submitting them. Ill-behaved clients will not validate and submit, but also not get back the reason why it failed (what would be the point - even not advisable from a security POV). Of course, server-side you should re-validate and somehow log invalid commands so Ops knows there are failures they need to resolve/look into. If you have clients in different technology, it might be useful to define the validation in a language neutral DSL and generate code in any tech/lang you like from that DSL (there other options here, though).

Upvotes: 0

L-Four
L-Four

Reputation: 13541

So this is the way I solved it. First, the main ValidationResult class looks like:

 public class ValidationResult
{        
    public List<ValidationResultItem> ValidationResultItems { get; set; }

    public bool IsAcceptable
    {
        get { return (ValidationResultItems == null || !ValidationResultItems.Any(vri => !vri.IsAcceptable)); }
    }       

    public void Add(ValidationResultItem propertyValidationResultItem)
    {
        ValidationResultItems.Add(propertyValidationResultItem);
    }

    public void Add(IEnumerable<ValidationResultItem> validationResultItems)
    {
        ValidationResultItems.AddRange(validationResultItems);
    }       
}

ValidationResultItem is an abstract class:

public abstract class ValidationResultItem
{
    private ResultType _resultType;

    protected ValidationResultItem(ResultType resultType, string message)
    {
        ResultType = resultType;
        Message = message;
    }

    public bool IsAcceptable { get; private set; }
    public string Message { get; private set; }
    public ResultType ResultType
    {
        get { return _resultType; }
        set { _resultType = value; IsAcceptable = (_resultType != ResultType.Error); }
    } 
}

and there are two implementations of it:

public class PropertyValidationResultItem : ValidationResultItem
{        
    public PropertyValidationResultItem(ResultType resultType, string message, string propertyName, object attemptedValue) : base(resultType, message)
    {            
        PropertyName = propertyName;           
        AttemptedValue = attemptedValue;
    }

    public string PropertyName { get; private set; }        
    public object AttemptedValue { get; private set; }             
}

and

public abstract class BusinessValidationResultItem : ValidationResultItem
{
    protected BusinessValidationResultItem(ResultType resultType, string message) : base(resultType, message)
    {
    }
}

Each command handler has its own implementation of BusinessValidationResultItem, for example:

public class AddArticleBusinessValidationResultItem : BusinessValidationResultItem
{
    public enum AddArticleValidationResultCode { UserDoesNotExist, UrlTitleAlreadyExists, LanguageDoesNotExist }

    public AddArticleBusinessValidationResultItem(ResultType resultType, string message, AddArticleValidationResultCode code)
        : base(resultType, message)
    {
        Code = code;
    }

    public AddArticleValidationResultCode Code { get; set; }
}

This means that if the client gets a ValidationResult, he can cast the BusinessValidationResultItem to the concrete AddArticleBusinessValidationResultItem and so use the specific enumeration in a switch statement - avoiding magic strings.

Upvotes: 2

B Z
B Z

Reputation: 9463

and this is not the best approach of course.

Why not? Whats wrong with strings? If you are worried about consistency maybe use resource files or constants. Strings will be more portable in between layers but that depends on your design. Regardless, you will probably want an ErrorCode (string or enum) and an ErrorMessage (string). I am assuming you need to convert this error into something more readable to the user?

You should look into the built in validation as mentioned in one of the comments. The validation comes from System.ComponentModel.DataAnnotations, nothing to do with MVC. You can validate outside the scope of MVC, here is an example:

var validationContext = new ValidationContext(yourObject, null, null);
var validationResults = new List<ValidationResult>();

Validator.TryValidateObject(yourObject, validationContext, validationResults);

HTH...

Upvotes: 0

Yannis
Yannis

Reputation: 6157

My REST api is quite similar in the sense that if there is a validation error then a string message is returned to the user together with an object.

For example:

[DataContract]
public class ApiErrorResult : ApiResult<IList<ErrorCodes>>
{
    public ApiErrorResult(String message)
    {
        Code = ApiCode.ValidationError;
        Error = message;
    }
}

then ApiResult is :

public class ApiResult<T>
{

    [DataMember]
    public ApiCode Code
    {
        get;
        set;
    }

    [DataMember]
    public String Error
    {
        get;
        set;
    }

    [DataMember]
    public T Context
    {
        get;
        set;
    }
}

So if it is a validation error then the context will contain the equivalent validation error codes. If it isnt i store the actual result in the context and return an ApiResult instead of an ApiErrorResult

hope this helps somehow.

Upvotes: 0

Related Questions