Basically the problem is that I want to perform validation against some values that I get form a database (EF) before I execute the BL. I'm currently using INotifyDataErrorInfo with attributes in the properties of my ViewModel. I tried to do this validation with a custom validator (CustomValidation attribute):
private string unit;
[Required(AllowEmptyStrings = false, ErrorMessage = Constants.Error6)]
[RegularExpression(Constants.AlphabeticRegEx, ErrorMessage = Constants.Error10)]
[CustomValidation(typeof(ProductSelectionViewModel),"IsInRegisteredUnits")]
public string Unit
{
get { return unit; }
set
{
if (value == unit)
return;
unit = value;
RaisePropertyChanged(vm => vm.Unit);
UpdateUnitPrice(selectedProduct, unit);
}
}
But the method in charge of performing this validation must be a static one, so under this scenario I cannot acces to my repository since it is not static.
public static ValidationResult IsInRegisteredUnits(object obj, ValidationContext context)
{
var productSelectionViewModel = (ProductSelectionViewModel)context.ObjectInstance;
if (!unitService.GetAllUnitsAbbreviation().Any(x=>x.Equals(productSelectionViewModel.Unit, StringComparison.CurrentCultureIgnoreCase)))
return new ValidationResult("La unidad ingresada no es vĂ¡lida", new List<string> { "Unit" });
return ValidationResult.Success;
}
How can I solve this (unitService.GetAllUnitsAbbreviation() cannot be a static method since its using a repository), maybe I'm performing this kind of validation in the worng place (wrong design), any help would be appreciated :)
Related
This is an extension of an older question from this post:
Enforcing a model's boolean value to be true using data annotations
This gave me a lot of insight on how to get the client side custom validation working with jquery-unubtrusive-ajax.js.
Here is the answer code:
namespace Checked.Entitites
{
public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return value != null && (bool)value == true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
//return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };
yield return new ModelClientValidationRule()
{
ValidationType = "booleanrequired",
ErrorMessage = this.ErrorMessageString
};
}
}
}
When i use this custom attribute in my models it works fine.
ex:
[BooleanRequired(ErrorMessage = "Please accept the terms")]
public bool Terms { get; set; }
When i use textboxfor in my views the error messages populate in the html validation summary.
#Html.CheckBoxFor(model => model.Terms, new { #class = "legalbox", #placeholder = "Terms" })
I also had to add this line to my jquery.unubtrusive-ajax.js
$.validator.unobtrusive.adapters.addBool("BooleanRequired", "required");
The issue i am having with this fix arises when i reference this model in the controller and check the modelstate. The modelstate is always false no matter what i have as the value for this custom validated field. It looks like the override isvalid is working in the client side validation but not on the server side. I need it to work on both and have been scouring trying to find a solution that isn't "ditch dataannotations and use something else".
The specific line i am using in my controller that will never pass with this field is as follows:
if (ModelState.IsValid) {
//Logic here
}
The rest of the model using the standard data-annotations validate correctly, i just cannot get this custom one to work the same way as the built in attributes. Its possible that the right solution would prevent me from having to add that line to the unobtrusive ajax file.
Any help would be appreciated.
Thanks
I am trying to validate nested objects (not models in the MVC senss) using annotations and some custom code.
I found the following post useful
Using Data Annotations Validation Manually and Object Graphs
As suggested in an answer, I've created an extra routine in the container class to validate the nested object. Here's my modified test code
public class Customer : IValidatableObject
{
public Customer()
{
Details = new CustomerDetails();
}
[Required]
[MaxLength(2)]
public string Name
{
get;
set;
}
public CustomerDetails Details
{
get;
private set;
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var context = new ValidationContext(this.Details, validationContext.ServiceContainer, validationContext.Items);
var results = new List<ValidationResult>();
Validator.TryValidateObject(this.Details, context, results);
return results;
}
}
However I have problems getting all the validation errors, even when calling TryValidateObject with validateAllProperties set to true.
var context = new ValidationContext(cs, null, null);
var results = new List<ValidationResult>();
Validator.TryValidateObject(cs, context, results,true);
If there are any errors in the container, only these will show. Only when there are no errors in the container object, errors in the nested object will show. I suspect it has something to do with the Validate rouine returning a full list, and not being able to add to an (existing) list from the container(?)
Are there any modifications I can make to routine to get all errors to show?
See this answer: https://stackoverflow.com/a/3400627/724944
So, there is an error in your class' atributes, and therefore Validate method doesn't get called.
I suggest using CustomValidationAttribute like this:
[CustomValidation(typeof(Customer), "ValidateRelatedObject")]
public CustomerDetails Details
{
get;
private set;
}
public static ValidationResult ValidateRelatedObject(object value, ValidationContext context)
{
var context = new ValidationContext(value, validationContext.ServiceContainer, validationContext.Items);
var results = new List<ValidationResult>();
Validator.TryValidateObject(value, context, results);
// TODO: Wrap or parse multiple ValidationResult's into one ValidationResult
return result;
}
I found a RequiredIfAttribute on the internet which I modified to RequiredNotIf. The attribute can be used like this.
[RequiredNotIf("LastName", null, ErrorMessage = "You must fill this.")]
public string FirstName { get; set; }
[RequiredNotIf("FirstName", null, ErrorMessage = "You must fill this")]
public string LastName { get; set; }
And the source code to the attribute...
[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)]
public class RequiredNotIfAttribute : RequiredAttribute, IClientValidatable
{
private string OtherProperty { get; set; }
private object Condition { get; set; }
public RequiredNotIfAttribute(string otherProperty, object condition)
{
OtherProperty = otherProperty;
Condition = condition;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(OtherProperty);
if (property == null)
{
return new ValidationResult(String.Format("Property {0} not found.", OtherProperty));
}
var propertyValue = property.GetValue(validationContext.ObjectInstance, null);
var conditionIsMet = !Equals(propertyValue, Condition);
return conditionIsMet ? base.IsValid(value, validationContext) : null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
var depProp = BuildDependentPropertyId(metadata, context as ViewContext);
var targetValue = (Condition ?? "").ToString();
if (Condition != null && Condition is bool)
{
targetValue = targetValue.ToLower();
}
rule.ValidationParameters.Add("otherproperty", depProp);
rule.ValidationParameters.Add("condition", targetValue);
yield return rule;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
var depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(OtherProperty);
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
{
depProp = depProp.Substring(thisField.Length);
}
return depProp;
}
}
The drawback with this - as I see it - is the magic string in the attribute "header". How can I get rid of it?
You can't get rid of it because attributes are metadata and values must be known at compile time. If you want to do more advanced validation without magic strings I would very strongly recommend you FluentValidation.NET. Performing validation with attributes in a declarative manner is very limiting IMHO. Just look at the quantity of source code you have to write for something as standard and easy as RequiredIf or RequiredNotIf. I don't know what the designers of the framework were thinking when they choose Data Annotations for validation. It's just ridiculous. Maybe in the future they will enrich it and allow for more complex scenarios but until then I stick with FV.
Assuming you mean the other property name; you can't. Attributes can only use a limited number of parameter types - Expression is not one of them, so you can't use the lambda trick (not that it would be a good idea anyway). And C# does not have a infoof / memberof operator. So all you have is things like strings.
Well, I guess you could add a non-magic key (i.e. one that doesn't tie directly to a member-name), but it seems massive overkill, for example:
// NOT a recommendation
[RequiredNotIf(1, ...)]
public string Foo {get;set;}
[SomeKey(1)]
public string Bar {get;set;}
This has removed the member-name, but still has a dependency on the key (1) resolving to another attributed member, and is more complex. It is also less clear, i.e. on a non-trivial class you might have to scan up and down to see which other member has the matching tag. I'm not a fan ;p
I am using the RegularExpressionAttribute from DataAnnotations for validation and would like to test my regex. Is there a way to invoke the attribute directly in a unit test?
I would like to be able to do something similar to this:
public class Person
{
[RegularExpression(#"^[0-9]{3}-[0-9]{3}-[0-9]{4}$")]
public string PhoneNumber { get; set; }
}
Then in a unit test:
[TestMethod]
public void PhoneNumberIsValid
{
var dude = new Person();
dude.PhoneNumber = "555-867-5309";
Assert.IsTrue(dude.IsValid);
}
Or even
Assert.IsTrue(dude.PhoneNumber.IsValid);
I ended up using the static Validator class from the DataAnnotations namespace. My test now looks like this:
[TestMethod]
public void PhoneNumberIsValid()
{
var dude = new Person();
dude.PhoneNumber = "666-978-6410";
var result = Validator.TryValidateObject(dude, new ValidationContext(dude, null, null), null, true);
Assert.IsTrue(result);
}
Just new up a RegularExpressionAttribute object.
var regularExpressionAttribute = new RegularExpressionAttribute("pattern");
Assert.IsTrue(regularExpressionAttribute.IsValid(objToTest));
Sorry for answering late.
I'm new here. If you want test every ValidationAttribute in isolate you can proceed to the next manner for example:
[Test]
public void Test_the_State_value_IsRequired()
{
string value = "Finished";
var propertyInfo = typeof(TimeoffTemporalIncapacityEntry).GetProperty("State");
var attribute = propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), true).Cast<RequiredAttribute>().FirstOrDefault();
Assert.IsTrue(attribute.IsValid(value));
}
I used the #Martin 's suggestion along with a static constants file which allowed me to avoid specifing the regex string locally
[TestMethod]
public void Test_Regex_NationalinsuranceNumber()
{
var regularExpressionAttribute = new RegularExpressionAttribute(Constants.Regex_NationalInsuranceNumber_Validate);
List<string> validNINumbers = new List<string>() { "TN311258F", "QQ123456A" };
List<string> invalidNINumbers = new List<string>() { "cake", "1234", "TS184LZ" };
validNINumbers.ForEach(p => Assert.IsTrue(regularExpressionAttribute.IsValid(p)));
invalidNINumbers.ForEach(p => Assert.IsFalse(regularExpressionAttribute.IsValid(p)));
}
You can use this class for validate any ValidationAttribute type in isolate:
T = class type containing the property,
A = type ValidationAttribute
Example:
string stateValue = "Pendiente";
ValidationAttributeValidator<ConfirmationTemporalIncapacityEntry, RequiredAttribute> validator =
new ValidationAttributeValidator<ConfirmationTemporalIncapacityEntry, RequiredAttribute>();
Assert.IsTrue(validator.ValidateValidationAttribute("State", stateValue));
public class ValidationAttributeValidator<T,A>
{
public ValidationAttributeValidator() { }
public bool ValidateValidationAttribute(string property, object value)
{
var propertyInfo = typeof(T).GetProperty(property);
var validationAttributes = propertyInfo.GetCustomAttributes(true);
if (validationAttributes == null)
{
return false;
}
List<ValidationAttribute> validationAttributeList = new List<ValidationAttribute>();
foreach (object attribute in validationAttributes)
{
if (attribute.GetType() == typeof(A))
{
validationAttributeList.Add((ValidationAttribute)attribute);
}
}
return(validationAttributeList.Exists(x => x.IsValid(value)));
}
}
Building on #Evelio's answer I am going to provide an answer to how do you unit test custom validators since this doesn't seem to be articulated anywhere on the internet and this is one of the top hits that come up when searching for how to do it.
#Evelio's answer is very close, but it could do with a bit more of an explanation.
To test your validation you need to have a class that attaches validation attributes to its member data. Here I am using a new custom validator that makes sense for my project called FeeTimeUnitValidator. This validator takes a range and another attribute as input. If the other attribute is zero, then the attribute the validator is attached to doesn't matter. But if the other attribute is not zero, then this attribute needs to be in the range.
Here is the MockClass I use for testing:
class MockClass
{
public decimal Fee { get; set; }
[FeeTimeUnitValidator(otherPropertyName:"Fee", minValue:1, maxValue:12)]
public int attributeUnderTest { get; set; }
public int badOtherProperty { get; set; }
[FeeTimeUnitValidator(otherPropertyName: "badOtherProperty", minValue: 1, maxValue: 12)]
public int badAttributeUnderTest { get; set; }
[FeeTimeUnitValidator(otherPropertyName: "NotFoundAttribute", minValue: 1, maxValue: 12)]
public int nameNotFoundAttribute { get; set; }
}
Notice the attribute validation:
[FeeTimeUnitValidator(otherPropertyName:"Fee", minValue:1, maxValue:12)]
This says to check the property "Fee" as the Fee property (i.e., it has to be non-zero) and then the range is 1 - 12.
I instantiate class in the unit test class and set it up with a setup method. Since there are three attributes on this class that have the validator, I pass in the name of the attribute into the setup class.
private MockClass classUnderTest;
private ValidationContext context;
FeeTimeUnitValidator setup(string attributeUnderTest)
{
classUnderTest = new MockClass();
classUnderTest.Fee = 0;
var propertyInfo = typeof(MockClass).GetProperty(attributeUnderTest);
var validatorArray = propertyInfo.GetCustomAttributes(typeof(FeeTimeUnitValidator), true);
Assert.AreEqual(1, validatorArray.Length);
var validator = validatorArray[0];
Assert.IsTrue(validator.GetType().Equals(typeof(FeeTimeUnitValidator)));
context = new ValidationContext(classUnderTest, null, null);
return (FeeTimeUnitValidator)validator;
}
There are a few things of interest. I am using #Evelio's approach to extract the validator from the attribute. This is doe in lines 3 and 4 of the setup routine. Then, since this is a unit test method, I do some asserts to make sure that I got what I expected. This actually caught a problem when I transferred this pattern to another unit test class for another validator.
Then the other key is that I create the ValidationContext (since the more complicated validators need a context to find the other attributes they refer to - in my case I use it to find the Fee attribute). When I was researching how to unit test these custom validators, what was tripping me up was the ValidationContext. I couldn't find any information about how to create them. I believe the "context" for the attribute validation is the class in which the attribute lives. This is why I create the validation context with the class instance as the first parameter. This then provides the validator with access to the other attributes on the class so you can do cross attribute validation.
Now that i have the context created and a pointer to a validator, I can jump into the unit test itself to ensure that the validator is doing its job properly:
[TestMethod]
public void TestInRangeIsValidWhenFeeNonZero()
{
// Arrange
var validator = setup("attributeUnderTest");
classUnderTest.Fee = 10;
// Act
ValidationResult value12 = validator.GetValidationResult(12, context);
ValidationResult value1 = validator.GetValidationResult(1, context);
ValidationResult value5 = validator.GetValidationResult(5, context);
// Assert
Assert.AreEqual(ValidationResult.Success, value12);
Assert.AreEqual(ValidationResult.Success, value1);
Assert.AreEqual(ValidationResult.Success, value5);
}
If my validator didn't need a context (i.e., it could validate the attribute without reference to the other attributes), then I could use the simpler interface of IsValid(), but if the validator needs a non-null context, you have to use the GetValidationResult() method like I have done here.
I hope this helps somebody else who might be writing validators and is as religious about unit testing as I am. :)
Here is a good article on creating custom validators.
Extending on #CobraGeek's answer and #Erik's comment, you can use the Validator.TryValidateProperty to validate only that one field instead of the whole object, as so:
var results = new List<ValidationResult>();
Person dude = new Person();
System.ComponentModel.TypeDescriptor.AddProviderTransparent
(new AssociatedMetadataTypeTypeDescriptionProvider(dude.GetType()), dude.GetType());
dude.PhoneNumber = "555-867-5309";
var vc = new ValidationContext(dude, null, null);
vc.MemberName = "PhoneNumber";
bool result = Validator.TryValidateProperty(dude.PhoneNumber, vc, results);
After which result is the boolean indicating success of the validation, and if false results contains the list of the details of the errors thrown.
// You can do something like this.
[TestMethod]
public void PhoneNumberIsValid
{
var propInfo = typeof(Person).GetProperty("PhoneNumber");
var attr = propInfo.GetCustomAttributes(typeof(RegularExpressionAttribute), true);
// Act Assert Positives
Assert.IsTrue(((RegularExpressionAttribute)attr [0]).IsValid("555-55-5555"));
// Act Assert Negative
Assert.IsFalse(((RegularExpressionAttribute)attr[0]).IsValid("123654654654"));
}
I have created a custom ResourceProvider to pull localization information from a database. I now want to use DataAnnotation to add validation to the model.
DataAnnotation has ErrorMessageResourceType and ErrorMessageResourceName properties but ErrorMessageResourceType only accepts System.Type (i.e. a compiled resource file)
Is there any way to get DataAnnotation to use the custom ResourceProvider?
I realize this is an old question, but wanted to add a bit. I found myself in the same situation and there doesn't appear to be any documentation/blogumentation on this topic. Nevertheless, I figured out a way to use a custom resource provider, with one caveat. The caveat is that I'm in an MVC application so I still have HttpContext.GetLocalResourceObject() available. This is the method that asp.net uses to localize items. The absence of the resource object doesn't stop you from writing our own solution, even if its a direct query of the DB tables. Nevertheless, I thought it was worth pointing out.
While I'm not terribly happy with the following solution, it seems to work. For each validation attribute I want to use I inherit from said attribute and overload the IsValid(). The decoration looks like this:
[RequiredLocalized(ErrorMessageResourceType= typeof(ClassBeginValidated), ErrorMessageResourceName="Errors.GenderRequired")]
public string FirstName { get; set; }
The new attribute looks like this:
public sealed class RequiredLocalized : RequiredAttribute {
public override bool IsValid(object value) {
if ( ! (ErrorMessageResourceType == null || String.IsNullOrWhiteSpace(ErrorMessageResourceName) ) ) {
this.ErrorMessage = MVC_HtmlHelpers.Localize(this.ErrorMessageResourceType, this.ErrorMessageResourceName);
this.ErrorMessageResourceType = null;
this.ErrorMessageResourceName = null;
}
return base.IsValid(value);
}
}
Notes
You need to decorate your code with the derived attribute, not the standard one
I'm using ErrorMessageResourceType to pass the type of the class being validated. By that I mean if I'm in a customer class and validating the FirstName property I would pass typeof(customer). I'm doing this because in my database backend I'm using the full class name (namespace + classname) as a key (the same way a page URL is used in asp.net).
MVC_HtmlHelpers.Localize is just a simple wrapper for my custom resource provider
The (semi-stolen) helper code looks like this ....
public static string Localize (System.Type theType, string resourceKey) {
return Localize (theType, resourceKey, null);
}
public static string Localize (System.Type theType, string resourceKey, params object[] args) {
string resource = (HttpContext.GetLocalResourceObject(theType.FullName, resourceKey) ?? string.Empty).ToString();
return mergeTokens(resource, args);
}
private static string mergeTokens(string resource, object[] args) {
if (resource != null && args != null && args.Length > 0) {
return string.Format(resource, args);
} else {
return resource;
}
}
I have used fluent validation to achieve this. It saves me lots of time. This is what my Globalized validator looks like. It does mean that you don't use data anotations, but sometimes data anotations get a bit big and messy.
Here is an example:
(Errors.Required, Labels.Email and Errors.AlreadyRegistered are in my blobal resources folder.)
public class CreateEmployerValidator : AbstractValidator<CreateEmployerModel> {
public RegisterUserValidator() {
RuleFor(m => m.Email)
.NotEmpty()
.WithMessage(String.Format(Errors.Required, new object[] { Labels.Email }))
.EmailAddress()
.WithMessage(String.Format(Errors.Invalid, new object[] { Labels.Email }))
.Must(this.BeUniqueEmail)
.WithMessage(String.Format(Errors.AlreadyRegistered, new object[] { Labels.Email }));
}
public bool BeUniqueEmail(this IValidator validator, string email ) {
//Database request to check if email already there?
...
}
}
Like I said, it is a move away form data annotations, only because I already have too many annotations on my methods already!
I'll add my findings since I had to fight with this. Maybe it will help someone.
When you derive from RequiredAttribute, it seems to break client side validation. So to fix this I implemented IClientValidatable and implemented the GetClientValidationRules method. Resources.GetResources is static helper method I have that wraps around HttpContext.GetGlobalResourceObject.
The custom required attribute:
public class LocalizedRequiredAttribute : RequiredAttribute, IClientValidatable
{
public LocalizedRequiredAttribute(string resourceName)
{
this.ErrorMessage = Resources.GetResource(resourceName);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = this.ErrorMessage,
ValidationType= "required"
};
}
}
Usage:
[LocalizedRequired("SomeResourceName")]
public string SomeProperty { get; set; }
And my Resources helper if anyone is interested:
public class Resources
{
public static string GetResource(string resourceName)
{
string text = resourceName;
if (System.Web.HttpContext.Current != null)
{
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
var globalResourceObject = context.GetGlobalResourceObject(null, resourceName);
if (globalResourceObject != null)
text = globalResourceObject.ToString();
}
return text;
}
}