Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Created December 29, 2014 10:19
Show Gist options
  • Save tugberkugurlu/5e895e6e0a9ef65bdaf7 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/5e895e6e0a9ef65bdaf7 to your computer and use it in GitHub Desktop.
using Nte.Http.Model.RequestCommands;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Http.ModelBinding;
namespace Nte.Http.Infrastructure
{
public class RequestCommandValidator
{
private readonly IRequestCommand _requestCommand;
private readonly ValidationContext _context;
public RequestCommandValidator(IRequestCommand requestCommand)
{
if (requestCommand == null)
{
throw new ArgumentNullException(nameof(requestCommand));
}
_requestCommand = requestCommand;
_context = new ValidationContext(requestCommand, serviceProvider: null, items: null);
}
public bool IsValid(out ModelStateDictionary modelStateDictionary)
{
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(_requestCommand, _context, results, true);
if (isValid == false)
{
var tempModelStateDictionary = new ModelStateDictionary();
results.ForEach(result =>
{
foreach (string memberName in result.MemberNames)
{
tempModelStateDictionary.AddModelError(memberName, result.ErrorMessage);
}
});
modelStateDictionary = tempModelStateDictionary;
}
else
{
modelStateDictionary = null;
}
return isValid;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment