Fluent Validation Inconsistent with ASP.NET MVC 5 - c#

I'm using Fluent Validation v5.5 with ASP.NET v5.2.2 and I'm getting some inconsistent results with the validation.
My view model is:
public class QuoteViewModel
{
[Display(Name = #"Day")]
public int DateOfBirthDay { get; set; }
[Display(Name = #"Month")]
public int DateOfBirthMonth { get; set; }
[Display(Name = #"Year")]
public int DateOfBirthYear { get; set; }
[Display(Name = #"Gender")]
public Gender? Gender { get; set; }
[Display(Name = #"State")]
public int StateId { get; set; }
}
My controller method is:
public ActionResult Quote(QuoteViewModel viewModel)
{
var _validator = new QuoteValidator();
var results = _validator.Validate(viewModel);
if (!ModelState.IsValid)
{
return Json(false);
}
return Json(true);
}
My validator is:
public class QuoteValidator : AbstractValidator<QuoteViewModel>
{
public QuoteValidator()
{
RuleFor(x => x.Gender).NotEmpty();
RuleFor(x => x.StateId).NotEmpty();
RuleFor(x => x.DateOfBirthDay).NotEmpty().InclusiveBetween(1, 31);
RuleFor(x => x.DateOfBirthMonth).NotEmpty().InclusiveBetween(1, 12);
RuleFor(x => x.DateOfBirthYear).NotEmpty().LessThanOrEqualTo(DateTime.UtcNow.Year);
}
}
I'm running a test that posts all blank value form fields. Thus the view model fields retain default values after the view model object is created.
For comparison, in the controller I'm running the validation explicitly and the results aren't consistent with the validation result in ModelState.
ModelState is showing 4 errors, all triggered by NotEmpty rules. NotEmpty on the nullable enum Gender doesn't seem to trigger.
The explicit validation is returning 7 out of 8 errors, the LessThanOrEqualTo rule won't fire since the DateOfBirthYear defaults to zero.
My pain point is I can't figure out why ModelState is missing the NotEmpty error on the nullable enum Gender.
The only way I've been able to trigger that error is to post just the Gender value.
Please help.
EDIT:
After stepping through some code, it appears that the issue is related to the Fluent Validation RequiredFluentValidationPropertyValidator. The Gender field is a nullable value type which is bound to null. The following snippet from RequiredFluentValidationPropertyValidator prevents validation:
ShouldValidate = isNonNullableValueType && nullWasSpecified;

!ModelState.IsValid doesn't use your validation result it uses defaulf MVC validation (that can be added through DataAnnotations). You have to check !results.IsValid instead which contains the validation result of your QuoteValidator.
If you want to use default ModelState.IsValid you have to mark your model with validator attribute:
[Validator(typeof(QuoteValidator))]
public class QuoteViewModel
{
[Display(Name = #"Day")]
public int DateOfBirthDay { get; set; }
[Display(Name = #"Month")]
public int DateOfBirthMonth { get; set; }
[Display(Name = #"Year")]
public int DateOfBirthYear { get; set; }
[Display(Name = #"Gender")]
public Gender? Gender { get; set; }
[Display(Name = #"State")]
public int StateId { get; set; }
}
And add the following line to your Application_Start method:
protected void Application_Start() {
FluentValidationModelValidatorProvider.Configure();
}

Related

Blazor trigger custom validation message

I have the following class which is being used as an input model for an EditForm in a Blazor server side application.
public class KundeInput
{
[ValidateComplexType]
public List<AnsprechpartnerInput> Ansprechpartner { get; } = new List<AnsprechpartnerInput>();
public string? Kundennummer { get; }
[Required]
[MaxLength(60)]
public string Firma { get; set; } = String.Empty;
[MaxLength(60)]
public string? Name2 { get; set; }
[MaxLength(60)]
public string? Name3 { get; set; }
}
As you can see, my model contains a list of another model called AnsprechpartnerInput. Here is this model:
public class AnsprechpartnerInput
{
public string? Kundennummer { get; set; }
public int Nummer { get; } = -1;
[MaxLength(60)]
[Required]
public string Vorname { get; set; } = String.Empty;
[MaxLength(60)]
[Required]
public string Nachname { get; set; } = String.Empty;
[MaxLength(40)]
[Required]
public string? Bereich { get; set; }
/ * More properties */
}
The validation works fine. However, once I have multiple invalid AnsprechpartnerInput models in my list, the ValidationSummary becomes a mess. Because it displays e.g. 5 times field xyz is invalid.
I know I can set a custom message with the ErrorMessage property but I am not able to use other attributes from my model in this message.
What I want to achive is this:
[Required(ErrorMessage = $"Vorname of {Kundennummer} is required")]
public string Vorname { get; set; } = String.Empty;
I already tried to change the message with reflection but accoridng to Microsoft this way is not recommend or supported
https://github.com/dotnet/aspnetcore/issues/25611
Is there any way to get it to work? I thought of string replacement but I am not sure how I can figure out the right model for my ValidationMessage.
Also is there any way to validate the items of the list by one and get a boolean result? Let's say I want to achive this:
#foreach (var ansprechpartner in Input.Ansprechpartner)
{
if (Input.SelectedAnsprechpartner is null)
Input.SelectedAnsprechpartner = ansprechpartner;
<a #onclick="() => Input.SelectedAnsprechpartner = ansprechpartner"
class="#GetNavListClass(Input.SelectedAnsprechpartner == ansprechpartner)"
id="list-ansprechpartner-tab-#(ansprechpartner.Nummer)"
data-toggle="list"
href="#list-ansprechpartner-#(ansprechpartner.Nummer)"
role="tab"
aria-controls="#(ansprechpartner.Nummer)">
#((MarkupString)(ansprechpartner.Nummer < 0 ? "<span class=\"font-weight-bold\">NEU</span>" : $"({ansprechpartner.Nummer})")) #ansprechpartner.Vorname #ansprechpartner.Nachname
</a>
// When the model ansprechpartner is invalid, I want to display an icon
}
Thanks for any help!
PS: Blazor rocks!
You should use a custom validation attribute where you can explicitly add any error message you want
public class KundennummerValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var model = (AnsprechpartnerInput)validationContext.ObjectInstance;
if(string.IsNullOrEmpty((string)value))
{
return new ValidationResult($"Vorname of {model.Kundennummer} is required", new[] { "Kundennummer" });
}
return ValidationResult.Success;
}
}
then use
[KundennummerValidation]
public string Vorname { get; set; } = String.Empty;
result :
Validation summary:

Validating form when model is a collection of sub models

I've got a view which needs several models to work correctly. So, I created a model which is a collection of multiple (sub) models. This is the model.
public class PolicyDetail
{
public Policy Policy { get; set; }
public IEnumerable<Insured> Insureds { get; set; }
public IEnumerable<Risk> Risks { get; set; }
public IEnumerable<Construction> Constructions { get; set; }
}
And here's an example of what one of the sub models look like, which is an actual entity from the database:
public class Policy
{
[Key]
public int PolicyID { get; set; }
[DisplayName("Policy Number")]
public Guid PolicyNumber { get; set; }
[Required(ErrorMessage = "Please enter a valid Effective Date.")]
[DataType(DataType.DateTime)]
[DisplayName("Effective Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime EffDate { get; set; }
[Required(ErrorMessage = "Please enter a valid Expiration Date.")]
[DataType(DataType.DateTime)]
[DisplayName("Expiration Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime ExpDate { get; set; }
public Boolean IsActive { get; set; }
}
This was all working well, right up until I tried to submit a form with errors in it to test the validation. I should have seen this coming (maybe?) but because the actual model doesn't have any validation tags on it, it always passes the if (ModelState.IsValid) check. Is there some way to enforce, or inherit, all of the Data Annotations from the sub classes?
Or, am I going about this all wrong, using a model which is a collection of other models? The thing is, I want to be able to edit/add multiple db entities from the same view.
EDIT:
This article by Josh Carroll looks to be EXACTLY what I need. But when I implement it, I get a Null Object error. Here's what I'm doing:
public class PolicyDetail
{
[Required, ValidateObject]
public Policy Policy { get; set; }
public IEnumerable<Insured> Insureds { get; set; }
public IEnumerable<Risk> Risks { get; set; }
public IEnumerable<Construction> Constructions { get; set; }
}
Then in the override method he provides:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var results = new List<ValidationResult>();
var context = new ValidationContext(value, null, null);
Validator.TryValidateObject(value, context, results, true);
if (results.Count != 0)
{
var compositeResults = new CompositeValidationResult(String.Format("Validation for {0} failed!", validationContext.DisplayName));
results.ForEach(compositeResults.AddResult);
return compositeResults;
}
return ValidationResult.Success;
}
}
the parameter "value" comes in null, so it errors on this line:
Validator.TryValidateObject(value, context, results, true);
Am I missing something? Doing something wrong?
You can manually call the validations on the sub-models using this: https://msdn.microsoft.com/en-us/library/dd411772.aspx
var context = new ValidationContext(model.Policy, serviceProvider: null, items: null);
var validationResults = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(model.Policy, context, validationResults, true);
You can then use the ModelState.AddModelError to build the response from that.
Definitely not the most elegant possible solution, but might be easier than rewriting what you have.

Model Binding Doesn't Match Value

I'm having a problem I can't seem to figure out here and I've done a fair amount of searching:
In my model (a list of objects) I have the following output:
<input data-val="true" data-val-number="Please enter a number." data-val-required="The ModelID field is required." id="Students_19__ModelID" name="Students[19].ModelID" type="hidden" value="62">
If you look closely here this value is 62 (I've bound a second object just to check myself and I see that it is also 62:
<input data-val="true" data-val-number="Please enter a number." id="Students_19__storage_ID" name="Students[19].storage.ID" type="hidden" value="62">
In the same view I'm seeing this:
#Html.LabelFor(_ => Model.Students[i].Show, "ID: " + Model.Students[i].storage.ID)
producing:
ID: 63
In summary:
#Html.HiddenFor(_ => Model.Students[i].storage.ID)
#Html.LabelFor(_ => Model.Students[i].Show, "ID: " + Model.Students[i].storage.ID)
OR
#Html.HiddenFor(m => m.Students[i].storage.ID)
#Html.LabelFor(m => m.Students[i].Show, "ID: " + Model.Students[i].storage.ID)
produces->
<input data-val="true" data-val-number="Please enter a number." id="Students_19__storage_ID" name="Students[19].storage.ID" type="hidden" value="62">
<label for="Students_19__Show">ID: 63</label>
Obviously 62 != 63 and this is throwing off the model in the controllers. Does anyone have an idea of what could be causing this? I feel like something is being converted poorly but I'm out of ideas at this point. I've seen this behavior before and shuffling around the loading order of the hidden fields has fixed it but this obviously isn't a good solution.
EDIT: Per comments:
The structure of the object is pretty tame: (this is the "storage" variable)
public class EducationGoalModel
{
public int? ID { get; set; }
public decimal Amount { get; set; }
public string Name { get; set; }
public string Category { get; set; }
//Education
public int StudentAge { get; set; }
public int StudentBegin { get; set; }
public int StudentYears { get; set; }
[DisplayFormat(DataFormatString = "{0:P2}", ApplyFormatInEditMode = true)]
[Percentage] //Custom annotation, nothing silly here
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Errors))] //Error is not triggered otherwise the ID wouldn't work in the "workaround"
public decimal Inflation { get; set; }
// This is just used by another module that needs annotations waaaay down the line, these values are unused.
public decimal TargetAmount { get { return Calculations.FutureValue(this.YearOfCompletion - DateTime.Now.Year, this.Inflation, this.Amount); } }
public byte RiskToleranceLevel { get; private set; }
public int YearOfCompletion { get; set; }
public bool Hide { get; set; }
public EducationGoalModel()
{
this.Category = FinanceGoalTargetCategory.EDUCATIONAL;
}
public EducationGoalModel(EducationGoal goal)
{
//The goal is just the entity I'm using, this is a light wrapper around it.
ID = goal.ID;
Amount = goal.Amount;
Name = goal.Name;
Category = goal.Category;
StudentAge = goal.StudentAge;
StudentBegin = goal.StudentBegin;
StudentYears = goal.StudentYears;
Inflation = goal.Inflation;
Hide = goal.Hide;
}
public void CopyTo(EducationGoal goal)
{ //SNIP.... we don't really care about this method, it isn't called
}
Here's the view Model:
public class EducationGoalInputModel : InputModelBase
{
public CurrencySliderModel AmountSlider { get; set; }
public EducationGoalModel storage { get; set; }
public int ModelID { get; set; }
public int StudentAge { get; set; }
public int StudentBegin { get; set; }
public int StudentYears { get; set; }
[MaxLength(20, ErrorMessageResourceName = "FinancialGoalsNameLength", ErrorMessageResourceType = typeof(Resources.Errors))]
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:P2}", ApplyFormatInEditMode = true)]
[Percentage]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Errors))]
public decimal Inflation { get; set; }
... plain constructor (no args), a second to construct and establish the "storage" object which is the one used for the above output.
Here's the base class, nothing interesting here really:
public abstract class InputModelBase { //a simple class that has
public abstract void UpdateAmounts(int age);
//and a couple other utility methods for the user interface (we support IE8 so a lot of UI information is stored)
}
EDIT: Per Hacks: because this is MVC (this works fine, but is terrible for maintenance and indicates a bigger problem)
<input type="hidden" name="#String.Format("Students[{0}].storage.ID", i)" id="#String.Format("Students_{0}__storage_ID", i)" value="#Model.Students[i].storage.ID" />
This outputs the correct values of value="63" using the example above.
EDIT #2
Based on feedback from the comments below *(thank you!) it looks like the ModelState doesn't agree with the Model. There's nothing obvious modifying the ModelState in the View that I can find but I've inherited this project and there's probably some extension method doing something that I need to track down. The values in this particular test 5. The ModelState shows the wrong value and thus the binding is wrong. This has not fixed the issue but is basically an accepted answer as I now know where to look.
Thanks for your help.

MVC data annotation on client side conditional

i have a form wherein there is conditional textboxes.i have used mvc dataannotation client side on dropdown change i hide two textboxes data validation error is not fired but in controller i get model error in if (ModelState.IsValid).How can i do condtional handling of data annotation in client side only.I dont want to use fullproof validation or other third party.
i tried removing the data-val-* attributes using jquery still getting error in controller.refer image if i select asset type laptop then sim plan and price is hidden dataannotation dont fire which is correct but get error on controller.
Model:
[Required(ErrorMessage = "Please Enter Make")]
public string Make { get; set; }
[Required(ErrorMessage = "Please Enter Model")]
public string Model { get; set; }
[Required(ErrorMessage = "Please Enter Sim Plan")]
public string SimPlan { get; set; }
[Required(ErrorMessage = "Please Enter Price")]
public decimal? Price { get; set; }
there's a much better way to add conditional validation rules in MVC3. Have your model inherit IValidatableObject and implement the Validate method:
public class Person : IValidatableObject
{
public string Name { get; set; }
public bool IsSenior { get; set; }
public Senior Senior { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (IsSenior && string.IsNullOrEmpty(Senior.Description))
yield return new ValidationResult("Description must be supplied.");
}
}
see more of a description at http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
If you trying to manually clear validation error which u have not used in your view than i would suggest you clear them before checking modelstate.
Ex:
[HttpPost]
public ActionResult Register(Model objModel )
{
foreach (string Key in ModelState.Keys)
{
if ((Key.Equals("Email")) || (Key.Equals("Password")))
{
ModelState[Key].Errors.Clear();
}
}
if (ModelState.IsValid)
{
//Do the work
}
}
In the above example i have passed the values in Model and i didn't pass any value for Email and password, so in controller i am clearing those Key which is present in ModelState.

Enum to Checkboxes in the Model C# MVC4

Now I was looking to make some validation for some checkbox fields in my model.
I want to create a unique rule that would require at least one checkbox to be true (or checked) in each category to make it valid. I have three different categories in this model.
I was told to approach this with enum as stated here.
I've looked into the situation and it seems a little over my head, because you basically utilize C# to customize your own rules.
Now these are the categories as mentioned in the hyperlink above:
//Disabilities
[Display(Name = "Learning Disabilities")]
public bool LD { get; set; }
[Display(Name = "Developmental Disabilities")]
public bool DD { get; set; }
[Display(Name = "AD/HD")]
public bool ADHD { get; set; }
[Display(Name = "Autism")]
public bool Autism { get; set; }
//Age Group
[Display(Name = "Child")]
public bool child { get; set; }
[Display(Name = "Youth")]
public bool youth { get; set; }
[Display(Name = "Adult")]
public bool adult { get; set; }
//Strategy Type
[Display(Name = "Academic")]
public bool academic { get; set; }
[Display(Name = "Behaviour")]
public bool behaviour { get; set; }
[Display(Name = "Communication")]
public bool communication { get; set; }
[Display(Name = "Social")]
public bool social { get; set; }
Now to approach this I was told to use enum:
public enum Age
{
[Display(Name="Child")
Child,
[Display(Name="Youth")
Youth,
[Display(Name="Adult")
Adult
}
^Do I throw this in the model still?
I know this goes into the model:
[Required]
public Age MyAge { get; set; }
After looking at several other examples I know that the above code is incomplete and I would also have to edit my view. As sad as it sounds, my education has not gone this far in programming so I apologize for my lack of understanding.
But if you could point me in the right direction so I can walk this golden brick road that would be much appreciated
Cheers.
Here is the small prototype I did for you with Enums and CheckBoxes and its validation.
Let your ENUM be -
public static class Data
{
public enum BloodGroup
{
[Description("A+")]
APositive,
[Description("B+")]
BPositive
}
}
Then construct your Enum model, which will hold the basic Checkbox properties -
public class EnumModel
{
public Data.BloodGroup BloodGroup { get; set; }
public bool IsSelected { get; set; }
}
Then construct Enum View Model based on Enum model, which basically have List of Enum Models -
public class EnumViewModel
{
public List<EnumModel> CheckBoxItems { get; set; }
}
Then your Controller Index Action, will construct EnumViewModel and will bind it to Index View -
public ActionResult Index()
{
EnumViewModel model = new EnumViewModel();
model.CheckBoxItems = new List<EnumModel>();
model.CheckBoxItems.Add(new EnumModel() { BloodGroup = Data.BloodGroup.APositive, IsSelected = false });
model.CheckBoxItems.Add(new EnumModel() { BloodGroup = Data.BloodGroup.BPositive, IsSelected = false });
return View(model);
}
Index View will display all the checkboxes and will make a POST to Submit action on click of submit button -
#model MVC.Controllers.EnumViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.ValidationSummary();
#using (Html.BeginForm("Submit", "Enum", FormMethod.Post))
{
for (int i = 0; i < Model.CheckBoxItems.Count; i++)
{
#Html.LabelFor(m => m.CheckBoxItems[i].BloodGroup);
#Html.CheckBoxFor(m => m.CheckBoxItems[i].IsSelected);
#Html.HiddenFor(m => m.CheckBoxItems[i].BloodGroup);
}
<input type="submit" value="click"/>
}
In the Submit Action We check for the IsSelected properties of the Enum View Model, if there are none, then we return error to Index View.
public ActionResult Submit(EnumViewModel model)
{
if (!model.CheckBoxItems.Where(p => p.IsSelected).Any())
{
ModelState.AddModelError("CheckBoxList", "Please select atleast one!!!");
return View("Index",model);
}
return View();
}
Output -
On Load -
When we do not select anything and submit the form -

Categories

Resources