Use validation on CheboxList in Asp.Net MVC4

Feb 27, 2013 at 4:52 PM
Hi,

I want use validator on a collection of checkbox (checkboxlist - this control don't yet exist), in my model, I create a collection of Object, and in my View, I parse this collection to create Html Element. For example :
<% foreach(var obj in MyModel.Coll)
{ %>
<input type="checbox" id="<%= obj.Id %>" value="<%= obj.Name %>">
<%} %>
How I can set validator on this property of this form (model) ?

Thank's

Laurent
Coordinator
Feb 27, 2013 at 5:26 PM
Hi

I'm not sure I entirely understand your question....FluentValidation is designed to validate pre-populated objects - not UI elements directly.

You'd need to populate a appropriate object model based on your control (by the looks of it, a collection of objects with properties Id and Name) and pass this into a validator that you've designed for validating this object. It's hard to give a concrete example of how to do this as you've not provided any details of how MyModel is defined...if you can provide some sample code then I can help further.

Jeremy
Mar 1, 2013 at 11:30 PM
Hi Jeremy

(Sorry for this late).
My wish will be to display a "checkboxlist" (list of checkbox, example: "Which activities use you ? 1. Tennis / 2. Football / 3. Hockey / ...") in a view. I want to display this liste (multichoice) in a view in asp.net MVC4, and to complete this view, add a validation (with fluent validation, to forced at least one choice). I dont't sure to represent correctly, first in my model, to use correctly FluentValidation.
Question, it's possible to do this kind of validation (at least one checkbox must be checked among the list of checkbox) with FluentValidation ? And could you give me a example (Model / Views / Controller) which use this system ?
Ps : I d'ont known if I was understand you ;)

Thanks a lot,

Laurent
Mar 23, 2013 at 11:27 AM
Hi Jeremy,

You haven't no idea for my answer ?

Laurent
Coordinator
Mar 25, 2013 at 11:35 AM
Hi Laurent

Yes, it is certainly possible to do this kind of validation. As I mentioned before, you'll need to represent your checkbox list as part of your model. You'd then render this in your view. You can then post back the selected items as a property of your viewmodel, which can be passed to a validator. I can't provide you with a full example, but here's a simplistic example that hopefully illustrates the point.
 public class MyModel {
  public SelectList Sports { get; set; }
  public IEnumerable<string> SelectedSports { get; set; }
  
  public MyModel() {
    Sports = new SelectList(new[] { "Tennis", "Football", "Hockey" });
  } 
}
...in your view, you'd iterate over the Sports property to build the checkbox list:
<form method="post" action="">
  @foreach(var sport in Model.Sports) {
    <input type="checkbox" name="SelectedSports" value="@sport" />@sport <br />
  }
  <input type="submit" value="Submit" />
</form>
Validator:
public class MyModelValidator : AbstractValidator<MyModel> {
  public MyModelValidator() {
    RuleFor(x => x.SelectedSports).Must(x => x != null && x.Count() > 0).WithMessage("Please select at least 1 sport");
  }
}
Controller:
public class MyController : Controller 
  public ActionResult Index() {
    return View(new MyModel());
  }
  
  [HttpPost]
  public ACtionResult Index(MyModel model) {
     var validator = new MyModelValidator();
     var results = validator.Validate(model);
     // ... check whether results are valid, if not, re-render view etc etc
  }
}
Apr 1, 2013 at 4:17 PM
Hi Jeremy,

Thank you for your example, but apparently, the method Must look don't work.
I have search and see few articles showing how implement the method "Must" with Fluent Validation but it's don't work.
And, I have another problem to get the value of checkboxes which are checked, I can know how many I have checked, but not know their ID (no useful to post the form and get values).
Below, this code how I have currently implement my validator
In View :
<% foreach (var newsLetterTypeItem in Model.NewsLetterTypes)
    { %>
        <input type="checkbox" name="SelectedNewsLetterTypes" id="<%= newsLetterTypeItem.Id %>" <%= ((newsLetterTypeItem.IsCheckedDefault) ? "checked=\"checked\"" : string.Empty)  %>/>
        <%= newsLetterTypeItem.Name %>
<% } %>
<%= Html.ValidationMessageFor(m => m.SelectedNewsLetterTypes) %>

And in Model :
public class NewsLetterModelValidator : AbstractValidator<NewsLetterModel>
{
public NewsLetterModelValidator()
{
    RuleFor(x => x.SelectedNewsLetterTypes).Must(IsValid).WithMessage("Please select at least 1 newletter");
}

private bool IsValid(List<object> lo)
{
    // I forced the value to false (to testing)
    return false;
}
}

Have you an idea on this problem, in my side I have no more ideas.

Laurent
Apr 2, 2013 at 8:33 AM
Same when I implement the validator on the check box, the test-validation client-side looks don't work, example :
RuleFor(x => x.IsAccepted).Equals(false).WithMessage("Condition must be checked");
Apr 2, 2013 at 9:19 AM
Same when I implement the validator on the check box, the test-validation client-side looks don't work, example :
RuleFor(x => x.IsAccepted).Equals(false).WithMessage("Condition must be checked");
Coordinator
Apr 15, 2013 at 10:14 AM
Could you elaborate what you mean by "the method Must look don't work"? Unless you provide details on what's not working there's no way I can help you!

As in my example, if you give all of the text boxes the same value for the "Name" field, then you can access them as an array from your controller and model.

In reply to your second post, "Equals" isn't a validator method - this is a .NET framework method for comparing objects. You need to use "Equal" instead.

Jeremy
Apr 17, 2013 at 11:14 AM
Hi,

I am facing issue in the following:

RuleFor(p => p.City).NotEmpty().Must(IsValidCountryCategory).WithMessage("Select a valid country");
    private bool IsValidCountryCategory(LegalAddressModel customer, string homeCountry)
    {
        // From here you can now access properties of the Customer directly
        return true;
    }
the above method is never triggered?

Also, I am not able to use 'When' Clause, however all the other rule works. I am not receiving any error but it is not working. I am using MVC4 and FluentValidation 3.4.6.0.

any help will be appreciated. Please keep me updated if anything am missing.
Coordinator
Apr 17, 2013 at 12:17 PM
How are you triggering the validator?
Apr 17, 2013 at 3:10 PM
Hi Jeremy,

If you want, I can do a basic sample (solution .sln) which implement the different problem. I hope it could help you.
Apr 18, 2013 at 7:04 AM
Edited Apr 18, 2013 at 7:18 AM
Hi,

here is my code

public class EntityAddressValidator: AbstractValidator<AddressModel>
{
    public EntityAddressValidator()
    {
        RuleFor(a => a.StreetAddress1).NotNull();
        RuleFor(a => a.StreetAddress2).NotNull();

       RuleFor(a => a.City).NotEmpty().Must(IsValidCountryCategory).WithMessage("Select a valid country");__
    }  
private bool IsValidCountryCategory(LegalAddressModel customer, string homeCountry)
{
    // From here you can now access properties of the Customer directly
    return true;
}
}

But using Must cluase I am unable to trigger IsValidCountryCategory() method. My requirement is dependent field validation, when country is US then state is required. If any one can help with the code will be great. Also I am validating throgh XML, I got to read and apply rules using XML only missing is must and when clause not working with fluentvalidation 3.4.6 and MVC 4.

Thanks waiting for response.
Coordinator
Apr 22, 2013 at 9:18 AM
Edited Apr 22, 2013 at 9:18 AM
@laurentb0204, feel free to send me a simple solution along with a description of the exact problem you're seeing. jeremy@jeremyskinner.co.uk @deepikashr are you using client-side validation? If so, then the client-side rules will execute first (such as NotNull/NotEmpty). Must rules are server-side only, so only once all the client rules have passed will the server rules execute. Could this explain the behaviour you're seeing?


Jeremy
Apr 26, 2013 at 12:23 PM
Hi,

I have attached file to use setvalidator. The issue is I am not able to use server side validation in fluent validation. Could u help me out its very difficult :(



Apr 26, 2013 at 12:23 PM
Did u get me mail.
Coordinator
Apr 26, 2013 at 12:51 PM
Yes, I received your email. I may not have the opportunity to look at it today, but I will try to take a look before Monday.

Jeremy
Coordinator
Apr 29, 2013 at 9:47 AM
@deepikashr, the files you sent me do not compile, so I'm afraid I can't test this out for you. If you'd like me to take a look at it, you'll need to put together a small sample that fully reproduces the issue and email me the entire solution. Thanks.
Apr 29, 2013 at 10:48 AM
Hey!! I sent mail just now. did u get it?