I'm using Foolproof Validation so I can use [RequiredIf] attributes on my view model. The problem is that I'd like to trigger validation within my code using the same logic outside a controller.
I've tried creating my own validation context and using Validatior.TryValidateObject; however, it fails with Foolproof's custom RequiredIf validator. Is there a way to take my model and validate it other than passing it to a controller?
Am I using the wrong approach?
Here is my code:
var draftModel = _draftHelper.LoadDraft(draftId);
var validationResults = new List<ValidationResult>();
var vc = new ValidationContext(draftModel, null, null);
var isValidDraft = Validator.TryValidateObject(draftModel, vc,
validationResults, true);
And the error I get is on the TryValidateObject line
System.NotImplementedException: The method or operation is not
implemented.
I think a better approach would be to use FluentValidation, not foolproof validation. I personally think Fluent is nicer than attributes too :).
Using FluentValidation, you are also able to validate your model without the use of a Controller.
DraftVM draft = draftRepository.Get(draftId);
var DraftValidator validator = new DraftVMValidator();
ValidationResult results = validator.Validate(draft);
public class DraftVMValidator : AbstractValidator<DraftViewModel>
{
public DraftVMValidator()
{
RuleFor(vm => vm.OptionalField)
.Must(BeFilledIfNameNotEmpty)
.WithMessage("Optional Field required because you filled out Name field");
}
public bool BeFilledIfNameNotEmpty(DraftVM viewModel)
{
return !string.IsNullOrWhiteSpace(viewModel.Name);
}
}
This will NOT give you a System.NotImplemented exception.
This validator is DRY because you can also plug it into ASP.NET MVC Validation.
You can simply call the following code in Global.asax or App_Start etc. One validator for all, bind it to MVC Model Validation or use it in any normal application.
FluentValidationModelValidatorProvider.Configure(); // This will bind it for you
If you use Inversion of Control container like Ninject, FluentValidation also has a plugin to work with that. More available on their documentation in link provided above.
I have a pretty big project example in my Github if you want to see more examples of this Validator instead of FoolProof. Example Validators with ASP.NET MVC 4
You need to let the MVC framework provide your Validator instead of using the Validator.TryValidateObject as below:
var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => viewModelToValidate, viewModelToValidate.GetType());
var compositeValidator = ModelValidator.GetModelValidator(modelMetadata, controller.ControllerContext);
foreach (ModelValidationResult result in compositeValidator.Validate(null))
{
validationResults.Add(new ValidationResult(result.Message, new List<string> { result.MemberName }));
}
Related
Can I take advantage of ASP.NET MVC model validation (using DataAnnotations for example) without an MVC View (and hence without the automatic model binding magic that you get with a view)?
As an example I might have a webhook hitting a controller action directly - no view - and I populate my model manually, but I still want to get the benefit of the DataAnnotation validations on my model's properties.
DataAnnotation is the part of System.ComponentModel.DataAnnotations.dll that comes along with .Net Framework.
Please feel free to use it.
The example you are giving me it looks like you want to expose Business Logic through WebApi.
Short answer is Yes, you can use.
However, on the top of it, have a look at expending your architecture by introducing WebApi, such that the code between MVC and WebApi is shared.
public class Recipe
{
[Required]
public string Name { get; set; }
}
var recipe = new Recipe();
var context = new ValidationContext(recipe, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(recipe, context, results);
if (!isValid)
{
foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
}
}
reference: http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx
I'm using VAB to validate some classes with attributes and I'm using a metadata class to share the same validation among different classes.
When i try to validate an object in the controller (btw i'm using asp.net mvc) the ValidationResults does not have errors and my entity should not be valid.
But, ASP.NET MVC does his magic because ModelState.IsValid is false. I guess the problem is the way I'm doing the manual validations.
In Global.asax I'm loading the associations between the classes and metadata classes.
Global.ASAX
private static void RegisterMetadataExtensions()
{
AssociatedMetadataTypeTypeDescriptionProvider typeDescriptionProvider;
typeDescriptionProvider =
new AssociatedMetadataTypeTypeDescriptionProvider(
typeof(FooViewModel), typeof(FooMetadata));
TypeDescriptor.AddProviderTransparent(typeDescriptionProvider,
typeof(FooViewModel));
typeDescriptionProvider =
new AssociatedMetadataTypeTypeDescriptionProvider(
typeof(FooCommand), typeof(FooMetadata));
TypeDescriptor.AddProviderTransparent(
typeDescriptionProvider, typeof(FooCommand));
}
Controller
[HttpPost]
public ActionResult Action(FooViewModel vm)
{
Validator<FooViewModel> validator =
ValidationFactory.CreateValidator<FooViewModel>();
ValidationResults res = validator.Validate(vm);
//res.Count is 0
OR
ValidationResults res = Validation.Validate<FooViewModel>(vm);
//res.Count is 0
//ModelState.IsValid is false
if(ModelState.IsValid)
Any idea is welcome.
Thanks in advanced.
I'm a big fan of the enterprise library, but I think a better way to do validation with MVC is to make your ViewModel implement IValidatableObject. That way, it automatically gets validated during the binding phase that sets ModelState.Isvalid
For your VAB validator to hook into ASP.NET MVC's validation I think you would need to implement ModelValidatorProvider and wrap the VAB validation results as described here ... http://bradwilson.typepad.com/blog/2009/10/enterprise-library-validation-example-for-aspnet-mvc-2.html
Up to now, most of our validation is performed using validation attributes on our view models.
One additional validation check we need to perform is to validate that a string doesn't already exist in our database.
Originally I was just handling this check within the controller action and then adding an error into ModelState if required. However, I would rather make use of the built-in validation infrastructure.
One method I tried was implementing IValidateableObject on my viewmodel. This feels a bit wrong as I'm calling DependencyResolver:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var viewModel = validationContext.ObjectInstance as EditPostViewModel;
if (viewModel != null)
{
var slug = (Slug)viewModel.Slug;
var repo = DependencyResolver.Current.GetService<IRepository<Post>>();
var existing = repo.Get(p => p.Slug == slug && p.Id != viewModel.Id);
if (existing != null)
yield return new ValidationResult("Duplicate slug.", new[] { "Slug" });
}
}
Another approach I thought about was using a custom ValidationAttribute. To me this only makes sense if I can re-use it on multiple viewmodels and to re-use it I need to be able to construct a generic repository interface (as per the above code) as I may need IRepository<Foo> or IRepository<Bar> depending on the Model.
Remote Validation is great but I still need to the validation server side.
So what would people recommend or have used themselves to achieve something similar.
Note that I do have unique database constraints on this column but don't want to fall back to exception handling to perform this validation.
Solution
I had a look as the asp.net article #Darin suggested. This approach definitely works, but the article is a bit flawed in that whilst it manages to decouple the validation service away from any direct references to ModelState, you instead end up with a circular dependency where controller depends on the validation service and the validation service depends on ModelState (via a wrapper); which doesn't exist until the controller is created. Nice!
Instead I exposed the IValidationDictionary as a public property on my validation service and set this in my controllers constructor:
slugValidator.ValidationDictionary = new ModelStateWrapper(this.ModelState);
The rest is kind of application specific but essentially I created a validator for each type of "slugable" entity I wanted to validate. These were then injected by my container.
public interface ISlugValidator<TEntity> where TEntity : ISlugable {
IValidationDictionary ValidationDictionary { get; set; }
bool ValidateSlug(Guid? entityId, Guid featureId, Slug slug);
}
I call ValidateSlug(...) just before I check ModelState.IsValid in my controller actions.
This is a good solution for the level of validation I need currently and the fact that most of it can be handled using Data annotations. If my validation/business rules get more complex I will probably switch to FluentValidation (this also works well with Depenency Injection) as it's better suited for externalizing validation logic.
I would recommend doing this type of validation at the service layer and not bother with data annotations.
I have been evaluating xVal as framework for validating Entities in the ASP.Net MVC Framework. I have recently discovered that each time a validation rule is broken, xVal cause an excpetion to be thrown. To me is seems incorrect. For example, when a user fills in a form, and forgets to fill three required fields , three exceptions will be thrown. Is this good practice? ( Edit: I also read this, so I guess its not good practice)
What are your experiences of using xVal? Is there good alternative validation framework that does not throw exceptions?
Thanks
(PS: I notice that lots of people are reading this, just to let you know I am using Fluent Validation now)
Have you looked at validation in Beta 2?
http://blogs.msdn.com/rickandy/archive/2009/10/03/client-side-validation-for-mvc-2-p2.aspx
No it's not a good practice to show exceptions instead of some simple messages because nothing seriously has been going wrong... You should instead populate ModelState with these errors and display them on the form using
Html.ValidationMessage("EntityPropertyName");
xVal supports all these. As well as validating on the client side before the form gets posted back.
Some code
When you set DataAnnotations attributes to your entity classes (or their Metadata companion classes) you will most likely also implement Validate() method. the best way would be to use T4 that will auto generate those for you, so you don't have to repeate the same code over and over...
public IEnumerable<ErrorInfo> Validate()
{
IList<ErrorInfo> errors = DataAnnotationsValidationRunner.GetErrors(this).ToList<ErrorInfo>();
return errors.AsEnumerable();
}
All you have to do then is to call this:
IEnumerable<ErrorInfo> errors = entityObjectInstance.Validate();
if (errors.Any())
{
new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, entityPropertyName);
}
And to automate this even further, you can implement this in an action filter, so validation will be automatic for your entity objects that get passed into controller action. Controller actions would only need to check whether ModelState.IsValid() then.
One more class you'll need here is (and is taken from the web somewhere):
public static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object instance)
{
var metadataAttribute = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
var metaClass = metadataAttribute != null ? metadataAttribute.MetadataClassType : instance.GetType();
var metaClassProperties = TypeDescriptor.GetProperties(metaClass).Cast<PropertyDescriptor>();
var modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();
return from metaProp in metaClassProperties
join modelProp in modelClassProperties on metaProp.Name equals modelProp.Name
from attribute in metaProp.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(modelProp.GetValue(instance))
select new ErrorInfo(metaProp.Name, attribute.FormatErrorMessage(string.Empty), instance);
}
}
MVC 2
Validation in Asp.net MVC 2 Beta 2 is similar to what xVal does. So if you're not too far into the project and you can consider using code in development progress as your foundation, maybe that is the way to go for you.
I think xVal is great, I've been using it with Castle Validators and it works perfectly. Just catch the RulesException whenever you're running validation and add the errors to your ModelState, e.g.
try
{
// execute validation runner
}
catch (RulesException ex)
{
ex.AddModelStateErrors(ModelState, "prefix");
}
ASP.NET MVC v2 will introduce its own validation framework.
I have a website where I allow users to create new Part records. I'm trying to figure out the best way to validate specific fields for uniqueness. I want to make sure that somebody doesn't try to add a Part with PartNumber 1234 if that PartNumber already exists on a different Part.
The Web Application is using Asp.net MVC with fluent nHibernate for mapping my objects to the database. I'm using Castle validation on my view models for things like ValidateNonEmpty, ValidateRange, etc. Should I use the ValidateSelf method to query the repository to see if that part number already exists? Something doesn't feel right about using my Repository on the ViewModel.
Would it be better for me to place that logic on the controller action? That doesn't seem right because I expect my ViewModel to already be Validated at the point (during ModelBind).
Or maybe its none of the above. Thanks for any help on this one.
UPDATE
Ok, not sure if this will help, but here is what my Save action looks like for a typical Create Action in my project:
public ActionResult Create(PartViewModel viewModel)
{
//I think I'd like to know if its Valid by this point, not on _repository.Save
if(ModelState.IsValid)
{
try
{
var part = _partCreateViewModelMap.MapToEntity(viewModel);
_repository.Save(part);
return Redirect("~/Part/Details/" + part.Id);
}
catch (Exception e)
{
// skip on down...
}
}
// return view to edit
return View(viewModel);
}
I have been asked this question many times. My friends were worried about whether they can perform data access from the validator code. The answer is simple. If you need to do this, you should do it. Usually we need to do such checks at each level of abstraction. And after all checks you should be ready to catch an exception, caused by unique constraint violation.
If you define a unique constraint within the database, then why not delegate the responsibility to check for whether a unique value already exists to the database? Using NHibernate, you can use the NHibernate.Exceptions.ISQLExceptionConverter interface to capture and transform known errors relating to constraint violations. You can also use NHibernate.Exceptions.IViolatedConstraintNameExtracter implementers (see NHibernate.Exceptions.TemplatedViolatedConstraintNameExtracter) to get at the grubby details of your database exception, and transform it into a user-friendly message, repackage as a validation exception of your chosing and catch it in the relevant controller.
Example of a quick, very specific quick and dirty exception converter from one of my projects:
Imports NHibernate
Imports NHibernate.Exceptions
Imports System.Data.SqlClient
Imports System.Data.Common
Namespace NHibernate
Public Class ConstraintViolationExceptionConverter
Implements ISQLExceptionConverter
Public Function Convert(ByVal adoExceptionContextInfo As Global.NHibernate.Exceptions.AdoExceptionContextInfo) As System.Exception Implements Global.NHibernate.Exceptions.ISQLExceptionConverter.Convert
Dim dbEx As DbException = ADOExceptionHelper.ExtractDbException(adoExceptionContextInfo.SqlException)
If TypeOf dbEx Is SqlException Then
Dim sqlError As SqlException = DirectCast(dbEx, SqlException)
Select Case sqlError.Number
Case 547
Return New ConstraintViolationException(adoExceptionContextInfo.Message, adoExceptionContextInfo.SqlException)
End Select
End If
Return SQLStateConverter.HandledNonSpecificException(adoExceptionContextInfo.SqlException, adoExceptionContextInfo.Message, adoExceptionContextInfo.Sql)
End Function
End Class
End Namespace
Configured through the web.config/nhibernate-configuration/session-factory property element:
<property name="sql_exception_converter">csl.NHibernate.ConstraintViolationExceptionConverter, csl</property>
Edit: Should probably mention that the converter interface has changed in recent versions of NHibernate, the interface from this example is from NHibernate.dll v2.1.0.4000
I typically put a Service layer between my controllers and repositories.
The service layer would then handle the validation and calls to the repository.
Then, if there's a validation error in the service layer, I throw a custom exception, catch it in the controller, and inject the errors in to the model state.
I have no answer for your question but you can check sharparchitecture.net site. It contains some best practives for asp.net mvc and nhibernate. Also I can recommend you to check xval project and tutorials about Validating with Data Annotation Validators
I have found the solution that works for me is to
1.) Ask if the entity is valid to execute your validation work.
2.) After this is complete you should have something on your object to show it's valid or not (in my case I use a CSLA like concept of "broken rules").
3.) If you have something like this you can verify the object is valid before NHibernate tries to persist it as shown below.
The only issue with this approach is that you do need to implement an interface on each entity requiring validation. If you can live with this it will stop NHibernate from persisting the changes of an object that's not valid according to your rules.
using System;
using NHibernate;
using NHibernate.Event;
using Validation.Entities.Interfaces;
using Persistence.SessionBuilder;
namespace Persistence.Validation
{
public class ValidationEventListener : IPreInsertEventListener, IPreUpdateEventListener
{
public bool OnPreInsert(NHibernate.Event.PreInsertEvent #event)
{
var entityToInsert = #event.Entity as IBusinessBase;
if (entityToInsert != null)
{
if (entityToInsert.BrokenRules != null)
{
RollbackTransactionBecauseTheEntityHasBrokenRules();
}
}
return false;
}
public bool OnPreUpdate(NHibernate.Event.PreUpdateEvent #event)
{
var entityToUpdate = #event.Entity as IBusinessBase;
if (entityToUpdate != null)
{
if (entityToUpdate.BrokenRules != null)
{
RollbackTransactionBecauseTheEntityHasBrokenRules();
}
}
return false;
}
private void RollbackTransactionBecauseTheEntityHasBrokenRules()
{
try
{
ISession session = SessionBuilderFactory.GetBuilder().CurrentSession;
if (session != null)
{
session.Transaction.Rollback();
}
}
catch (Exception ex)
{
//this will force a rollback if we don't have a session bound to the current context
throw new NotImplementedException();
}
}
}
}
I would say this matters on your architecture. With MVC apps that I have done in the past we abstract away the domain stuff away from the web stuff and naturally we use dependency injection to avoid hard dependencies.
When it comes to validating the model when you are in the act of binding it, yes you could easily use the service, repository, or whatever you have next in your architecture in a ValidateSelf method. I think the question rises of what about that dependency.
If I remember correctly you can create your own custom binder that will use your dependency injection framework to plug-in any services your model needs for validation when you create it, call MVC's default binder to fill in the object, then call into Castle Validation's framework to do the validation. This isn't a fully thought solution, but hopefully it provokes some ideas.