Created
December 29, 2014 10:19
-
-
Save tugberkugurlu/5e895e6e0a9ef65bdaf7 to your computer and use it in GitHub Desktop.
RequestCommandValidator - Manual Validator. Refer to: http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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