C# Unable to find other properties in custom validation attribute - c#

Trying to make my own Validation Attribute that uses a property name to find another property.
Currently, I am having problems finding the other property. It seems I am unable to find this property (or in fact any properties).
The check for property == null is always coming up as true.
Any ideas why I wouldn't be able to find properties?
This is the custom filter I have made
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectInstance.GetType().GetProperty(PropertyName);
if (property == null)
{
return new ValidationResult(string.Format(
"Unknown property {0}",
new[] { PropertyName }
));
}
var propertyValue = property.GetValue(validationContext.ObjectInstance);
// Just for testing purposes.
return new ValidationResult(ErrorMessage);
}
This is the model I am using behind my razor view.
public class OrganisationDetailsModel : PageModel
{
private readonly FormStateContext _context;
public OrganisationDetailsModel(FormStateContext context)
{
_context = context;
}
[BindProperty]
[RegularExpression(pattern: "(yes|no)")]
[Required(ErrorMessage = "Please select if you are registered on companies house")]
public string CompanyHouseToggle { get; set; }
[BindProperty]
[StringLength(60, MinimumLength = 3)]
[RequiredIf("CompanyHouseToggle")]
public string CompanyNumber { get; set; }
[BindProperty]
[StringLength(60, MinimumLength = 3)]
[Required(ErrorMessage = "Enter your organisation name")]
public string OrganisationName { get; set; }
[BindProperty]
[RegularExpression(pattern: "(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})", ErrorMessage = "This VAT number is not recognised")]
[Required(ErrorMessage = "Enter your vat number")]
public string VatNumber { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
return RedirectToPage("ApplicantDetails");
}
I appreciate the fact that the custom validation attribute doesn't really do anything at the moment but that is becuase I have become stuck on this issue.
Thanks for any help.

Let's use the following code snippet to help explain what is going on here:
protected override ValidationResult IsValid(object value, ValidationContext ctx)
{
var typeFullName = ctx.ObjectInstance.GetType().FullName;
...
}
In this example, you might expect typeFullName to be XXX.OrganisationDetailsModel, but it isn't: it's actually System.String (the type of the property you’re trying to validate). System.String clearly does not have a property named e.g. CompanyHouseToggle and so GetProperty rightly returns null.
I've not seen many cases where [BindProperty] has been used more than once on a PageModel. It's certainly possible, but it appears that each property is treated as being individual and that the PageModel itself is not being validated.
In order to work around this, you can just turn your individual properties into a complex type and use that instead. The docs and examples use an inline class for this, inside of the PageModel class. Here's an example of an updated OrganisationDetailsModel class:
public class OrganisationDetailsModel : PageModel
{
...
[BindProperty]
public InputModel Input { get; set; }
public void OnGet() { }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
return Page();
return RedirectToPage("ApplicantDetails");
}
public class InputModel
{
[RegularExpression(pattern: "(yes|no)")]
[Required(ErrorMessage = "Please select if you are registered on companies house")]
public string CompanyHouseToggle { get; set; }
[StringLength(60, MinimumLength = 3)]
[RequiredIf("CompanyHouseToggle")]
public string CompanyNumber { get; set; }
...
}
}
This includes the following changes:
Creation of an InputModel class to hold all properties.
Removal of all other properties that have now moved into InputModel.
Addition of an Input property of type InputModel, that gets bound using [BindProperty].
Removed [BindProperty] from the original properties that have now been moved.
The last step is to replace any usage of e.g. CompanyNumber with Input.CompanyNumber in the PageModel's corresponding .cshtml and to ensure you use the Input. prefix when accessing properties within the PageModel class itself.

By the doc. getProperties() only return publics.
https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=netframework-4.7.2
So if want to get non-public properties. Find on belows.
Get protected property value of base class using reflections
protected override ValidationResult IsValid(object value, ValidationContext context) {
var property = context.ObjectType.getProperty(context.MemberName);
// TODO
return ValidationResult.Success;
}

Related

Apply data annotations validation to all properties of same primitive datatype in a viewmodel

I searched google and SO for my scenario but not able to find an answer. I want to create a regular expression data annotation validation in a viewmodel class properties which are of double type. Since I have around 20 properties of type double. So I want to create a custom regular expression validation and apply to all double type properties without explicitly specifying on each property like:
[RegularExpression(#"^[0-9]{1,6}(\.[0-9]{1,2})?$", ErrorMessage ="Invalid Input")]
public double Balance { get; set; }
I am expecting thing like this:
[ApplyRegExpToAllDoubleTypes]
public class MyModel
{
public double Balance { get; set; }
public double InstallmentsDue { get; set; }
}
That's an interesting question. Here is how it can be done:
Define a custom ValidationAttribute and apply it at the class level by setting AttributeTargets.Class. Inside the ValidationAttribute, use reflection to get the double properties, then validate the value of each property. If any of the validations fail, return a validation failed message.
[ApplyRegExpToAllDoubleTypes]
public class MyModel {
public double Balance { get; set; }
public double InstallmentsDue { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class ApplyRegExpToAllDoubleTypes : ValidationAttribute {
protected override ValidationResult IsValid(object currentObject, ValidationContext validationContext) {
if (currentObject == null) {
return new ValidationResult("Object can't be null");
}
var properties = validationContext.ObjectType.GetProperties().Where(x => x.PropertyType == typeof(double));
foreach (var property in properties) {
//Here I compare the double property value against '5'
//Replace the following with the custom regex check
if ((double)property.GetValue(currentObject) < 5) {
return new ValidationResult("All double properties must be greater than 5");
}
}
return ValidationResult.Success;
}
}

Hide the underlying property name in Data Annotation validation error message

I have this asp.net core model:
public class MyModel
{
[ModelBinder(Name = "id")]
[StringLength(36, MinimumLength = 3)]
public string ObjectId { get; set; }
}
I added the ModelBinder attribute in order to rename the "ObjectId" field to "id".
When I trying to submit the model with bad values. For example:
{
"id": "1111111111111111111111111111111111111111111111111111111111111111111111111111"
}
I'm getting back this response from the server:
{
"id":["The field ObjectId must be a string with a minimum length of 3 and a maximum length of 36."]
}
Expected output:
{
"id":["The field id must be a string with a minimum length of 3 and a maximum length of 36."]
}
That's strange because the key ("id") was written in the right case. But in the value ("ObjectId") it was written in wrong.
My client shouldn't be aware of ObjectId. He just know id. How to fix messages like these?
Thanks.
The solution is to use DisplayName attribute:
public class MyModel
{
[ModelBinder(Name = "id")]
[StringLength(36, MinimumLength = 3)]
[DisplayName("id")]
public string Id {get; set;}
}
You can set a custom error message on StringLengthAttribute Class.
public class MyModel
{
[ModelBinder(Name = "id")]
[StringLength(36, MinimumLength = 3, ErrorMessage="The field id must be a string with a minimum length of {1} and a maximum length of {2}.")]
public string ObjectId { get; set; }
}
Excerpt from documentation page:
You can use composite formatting placeholders in the error message: {0} is the name of the property; {1} is the maximum length; and {2} is the minimum length. The placeholders correspond to arguments that are passed to the String.Format method at runtime.
For StringLength, it uses the default property name for constructing the error message which is expected.
If you prefer using the Name arugment from ModelBinder, you could implement your own StringLength arribute like
public class CustomStringLength : StringLengthAttribute
{
public CustomStringLength(int maximumLength)
: base(maximumLength)
{
}
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyName = validationContext.DisplayName;
var propertyAttribute = validationContext.ObjectType
.GetProperty(propertyName)
.GetCustomAttribute(typeof(ModelBinderAttribute));
if (propertyAttribute is ModelBinderAttribute modelBinderAttribute)
{
validationContext.DisplayName = modelBinderAttribute.Name;
}
//validationContext.DisplayName = "Id";
return base.IsValid(value, validationContext);
}
}
Then use it like
public class MyModel
{
[ModelBinder(Name = "id")]
[CustomStringLength(36, MinimumLength = 3)]
public string ObjectId { get; set; }
}

Passing parameter to a custom validation attribute in ASP.NET MVC

I'm using ASP.NET MVC and I wanna create a custom validation attribute to validate StartTime and EndTime which refer from the text inputs.
I have tried:
Model:
public class MyModel
{
public bool GoldTime { get; set; }
[TimeValidation(#"^\d{1,2}:\d{1,2}$", GoldTime, ErrorMessage = "Start time is invalid.")]
public string StartTime { get; set; }
[TimeValidation(#"^\d{1,2}:\d{1,2}$", GoldTime, ErrorMessage = "End time is invalid.")]
public string EndTime { get; set; }
}
Validation attribute:
public class TimeValidationAttribute : ValidationAttribute
{
private readonly string _pattern;
private readonly bool _useGoldTime;
public TimeValidationAttribute(string pattern, bool useGoldTime)
{
_pattern = pattern;
_useGoldTime = useGoldTime;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_useGoldTime)
{
var regex = new Regex(_pattern);
if (!regex.IsMatch(value.ToString()))
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
}
But I'm getting this error message:
An object reference is required for the non-static field, method, or
property 'MyModel.GoldTime'
Then, I've tried again by changing GoldTime (in the model) to true, the error message would disappear.
So, my question is: How can I pass the parameter GoldTime to the attribute constructor? I need to use the GoldTime as a key to enable validating the value of StartTime and EndTime.
Thank you!
It is complaining about using a model property within the attribute definition. Instead, within your custom attribute, you can use properties on the ValidationContext class to get the underlying model, I think via validationContext.ObjectInstance.
Obviously, you don't want to hard-code the type of model but you could use reflection:
bool goldTime;
var prop = validationContext.ObjectInstance.GetType().GetProperty("GoldTime");
if (prop != null)
goldTime = (bool)prop.GetValue(validationContext.ObjectInstance, null);
Or, define an interface for the model:
public interface ITimeModel
{
bool GoldTime { get; set; }
}
And look for that:
bool goldTime;
if (validationContext.ObjectInstance is ITimeModel)
goldTime = ((ITimeModel)validationContext.ObjectInstance).GoldTime;

IValidateObject not showing message mvc

My Model:
public class FPTAssetSummary : IValidatableObject
{
[Required]
[Display(Name = "New Version")]
public int ForatFrom { get; set; }
[Required]
[Display(Name = "Old Version")]
public int ForatTo { get; set; }
public List<FPTFORATExcel> FPTForatVersionList { get; set; }
public IEnumerable<ValidationResult> Validate(
ValidationContext validationContext)
{
if (ForatFrom <= ForatTo)
{
yield return new ValidationResult(
"Old version must be higher than the new version");
}
}
}
My Controller:
[HttpPost]
public ActionResult ForatExcelCompare(FPTAssetSummary foratcompare)
{
var ExcelIDFrom = foratcompare.ForatFrom;
var ExcelIDTo = foratcompare.ForatTo;
return RedirectToAction("Index", new
{
ForatFrom = ExcelIDFrom,
ForatTo = ExcelIDTo
});
}
Currently I am posting two integers from a view (2 dropdownboxes), to the controller below and passing the two values into the index with the two parameters (ForatFrom and ForatTo).
However my IValidationObject method isn't returning the ValidationResult message. I think I need to check the model state in the ForatExcelCompare method, however I need to be able to return to the previous controller with the error message if the model state is false. Any Ideas?

DataAnnotations "NotRequired" attribute

I've a model kind of complicated.
I have my UserViewModel which has several properties and two of them are HomePhone and WorkPhone. Both of type PhoneViewModel. In PhoneViewModel I have CountryCode, AreaCode and Number all strings. I want to make the CountryCode optional but AreaCode and Number mandatory.
This works great. My problem is that in the UserViewModel WorkPhone is mandatory, and HomePhone is not.
Is there anyway I can dissable Require attributs in PhoneViewModel by setting any attributes in HomeWork property?
I've tried this:
[ValidateInput(false)]
but it is only for classes and methods.
Code:
public class UserViewModel
{
[Required]
public string Name { get; set; }
public PhoneViewModel HomePhone { get; set; }
[Required]
public PhoneViewModel WorkPhone { get; set; }
}
public class PhoneViewModel
{
public string CountryCode { get; set; }
public string AreaCode { get; set; }
[Required]
public string Number { get; set; }
}
[UPDATED on 5/24/2012 to make the idea more clear]
I'm not sure this is the right approach but I think you can extend the concept and can create a more generic / reusable approach.
In ASP.NET MVC the validation happens at the binding stage. When you are posting a form to the server the DefaultModelBinder is the one that creates model instances from the request information and add the validation errors to the ModelStateDictionary.
In your case, as long as the binding happens with the HomePhone the validations will fire up and I think we can't do much about this by creating custom validation attributes or similar kind.
All I'm thinking is not to create model instance at all for HomePhone property when there are no values available in the form (the areacode, countrycode and number or empty), when we control the binding we control the validation, for that, we have to create a custom model binder.
In the custom model binder we are checking if the property is HomePhone and if the form contains any values for it's properties and if not we don't bind the property and the validations won't happen for HomePhone. Simply, the value of HomePhone will be null in the UserViewModel.
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "HomePhone")
{
var form = controllerContext.HttpContext.Request.Form;
var countryCode = form["HomePhone.CountryCode"];
var areaCode = form["HomePhone.AreaCode"];
var number = form["HomePhone.Number"];
if (string.IsNullOrEmpty(countryCode) && string.IsNullOrEmpty(areaCode) && string.IsNullOrEmpty(number))
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
Finally you have to register the custom model binder in global.asax.cs.
ModelBinders.Binders.Add(typeof(UserViewModel), new CustomModelBinder());
So now of you have an action that takes UserViewModel as parameter,
[HttpPost]
public Action Post(UserViewModel userViewModel)
{
}
Our custom model binder come into play and of form doesn't post any values for the areacode, countrycode and number for HomePhone, there won't be any validation errors and the userViewModel.HomePhone is null. If the form posts atleast any one of the value for those properties then the validation will happen for HomePhone as expected.
I've been using this amazing nuget that does dynamic annotations: ExpressiveAnnotations
It allows you to do things that weren't possible before such as
[AssertThat("ReturnDate >= Today()")]
public DateTime? ReturnDate { get; set; }
or even
public bool GoAbroad { get; set; }
[RequiredIf("GoAbroad == true")]
public string PassportNumber { get; set; }
Update: Compile annotations in a unit test to ensure no errors exist
As mentioned by #diego this might be intimidating to write code in a string, but the following is what I use to Unit Test all validations looking for compilation errors.
namespace UnitTest
{
public static class ExpressiveAnnotationTestHelpers
{
public static IEnumerable<ExpressiveAttribute> CompileExpressiveAttributes(this Type type)
{
var properties = type.GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(ExpressiveAttribute)));
var attributes = new List<ExpressiveAttribute>();
foreach (var prop in properties)
{
var attribs = prop.GetCustomAttributes<ExpressiveAttribute>().ToList();
attribs.ForEach(x => x.Compile(prop.DeclaringType));
attributes.AddRange(attribs);
}
return attributes;
}
}
[TestClass]
public class ExpressiveAnnotationTests
{
[TestMethod]
public void CompileAnnotationsTest()
{
// ... or for all assemblies within current domain:
var compiled = Assembly.Load("NamespaceOfEntitiesWithExpressiveAnnotations").GetTypes()
.SelectMany(t => t.CompileExpressiveAttributes()).ToList();
Console.WriteLine($"Total entities using Expressive Annotations: {compiled.Count}");
foreach (var compileItem in compiled)
{
Console.WriteLine($"Expression: {compileItem.Expression}");
}
Assert.IsTrue(compiled.Count > 0);
}
}
}
I wouldn't go with the modelBinder; I'd use a custom ValidationAttribute:
public class UserViewModel
{
[Required]
public string Name { get; set; }
public HomePhoneViewModel HomePhone { get; set; }
public WorkPhoneViewModel WorkPhone { get; set; }
}
public class HomePhoneViewModel : PhoneViewModel
{
}
public class WorkPhoneViewModel : PhoneViewModel
{
}
public class PhoneViewModel
{
public string CountryCode { get; set; }
public string AreaCode { get; set; }
[CustomRequiredPhone]
public string Number { get; set; }
}
And then:
[AttributeUsage(AttributeTargets.Property]
public class CustomRequiredPhone : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = null;
// Check if Model is WorkphoneViewModel, if so, activate validation
if (validationContext.ObjectInstance.GetType() == typeof(WorkPhoneViewModel)
&& string.IsNullOrWhiteSpace((string)value) == true)
{
this.ErrorMessage = "Phone is required";
validationResult = new ValidationResult(this.ErrorMessage);
}
else
{
validationResult = ValidationResult.Success;
}
return validationResult;
}
}
If it is not clear, I'll provide an explanation but I think it's pretty self-explanatory.
Just some observation: the following code couse a problem if the binding is more than simple filed. I you have a case that in object have nested object it going to skip it and caouse that some filed not been binded in nested object.
Possible solution is
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (!propertyDescriptor.Attributes.OfType<RequiredAttribute>().Any())
{
var form = controllerContext.HttpContext.Request.Form;
if (form.AllKeys.Where(k => k.StartsWith(string.Format(propertyDescriptor.Name, "."))).Count() > 0)
{
if (form.AllKeys.Where(k => k.StartsWith(string.Format(propertyDescriptor.Name, "."))).All(
k => string.IsNullOrWhiteSpace(form[k])))
return;
}
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
much thanks to Altaf Khatri

Categories