MVC Form Validation

Last post 09-22-2008 3:27 AM by peboo. 26 replies.

Sort Posts:

  • MVC Form Validation

    12-25-2007, 1:50 AM
    • Member
      67 point Member
    • ronnyek
    • Member since 07-27-2006, 6:49 PM
    • Posts 24
    #1) I've till now, seen absolutely 0 examples of how to handle any sort of validation, and would like to see anythign that would help out there. #2) Can server controls be used?
    Weston Weems

    Ikarii Software
  • Re: MVC Form Validation

    12-25-2007, 8:27 AM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    Excellent remark! I am also looking for something for validating my forms with the MVC Framework. Can someone help? 

  • Re: MVC Form Validation

    12-25-2007, 12:23 PM

    ronnyek:
    Can server controls be used?
     

    If you meant the validation controls, they cannot be used (yet?) because they validate other server controls, which in turn require a form with runat=server.

    It's possible and probable that the MVC team will provide validation helpers (or even the MVC cotrib project) for client-side validation. The other half of the story is the server-side validation, which will be split into model code that validates the fields and controller code that reports validation problems to the user. See the following fictitious code:

     

    [ControllerAction]
    public void Create()
    {
      Product prod = new Product();
      prod.UpdateFrom(Request.Form);
    
      ValidationResult result;
      result = product.Validate();
      if(result.Success)
      {
         ProductRepository.Save(prod);
         RedirectToAction("List");
      }
      else //validation failed
      {
        TempData["validationErrors"] = result.GetErrorMessages();
        RedirectToAction("New");  
      }
    }
      
    __________________________________________
    Sergio Pereira
    http://devlicio.us/blogs/sergio_pereira/
  • Re: MVC Form Validation

    12-25-2007, 1:43 PM
    • Member
      87 point Member
    • stribny
    • Member since 05-24-2007, 9:02 PM
    • KobeÅ™ice, Czech republic
    • Posts 24
  • Re: MVC Form Validation

    12-25-2007, 2:16 PM
    • Member
      574 point Member
    • abombss
    • Member since 06-27-2006, 4:13 PM
    • Chicago, IL
    • Posts 164

     Look at jquery validate... Its the best client side validation framework I have found thus far.  As we work on Client Script support for Mvc Contrib I am hoping to include validation in some way to make it easier.

    Adam Tybor -- abombss.com
  • Re: MVC Form Validation

    12-28-2007, 6:16 AM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

     @ Sergio Pereira:

    How can I use ValidationResult ?

    (I use LINQ).

    It would be great if you could provide another fictitious code.

    Thank you. 

  • Re: MVC Form Validation

    12-28-2007, 11:22 AM
    Answer

    OK. More fictitious code to the rescue.

      

    public partial class Product
    {
      public ValidationResult Validate()
      {
         ValidationResult result = new ValidationResult();
    
         if(this.Name.IndexOfAny('~', '!', '^'))
         {
            result.AddError("The product Name has invalid characters.");
         }
    
         if(this.UnitPrice < 0.0)
         {
            result.AddError("The product price cannot be negative.");
         }
    
         //..and so on...
    
         return result;
      }
    }
    
    public class ValidationResult
    {
      public ValidationResult() {  }
    
      private List<string> messages = new List<string>();
      public bool Success {get{ return messages.Count > 0;} }
    
      public void AddError(string errorMsg)
      {
        messages.Add(errorMsg);
      }
      
      public string[] GetErrorMessages()
      {
        return messages.ToArray();
      }
    }
     

    Needless to say, this is not tested and based on more complex real code. 

    __________________________________________
    Sergio Pereira
    http://devlicio.us/blogs/sergio_pereira/
  • Re: MVC Form Validation

    12-28-2007, 11:45 AM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    @ Sergio Pereira:

    Thanks! It looks great!

    However, there is a little something I quite don't understand.

    Is there something in common between your class ValidationResult and this one:

    http://msdn2.microsoft.com/en-us/library/system.windows.controls.validationresult.aspx

    ?
     

  • Re: MVC Form Validation

    12-28-2007, 12:22 PM

    dimi3:

    Is there something in common between your class ValidationResult and this one:

    http://msdn2.microsoft.com/en-us/library/system.windows.controls.validationresult.aspx

    Yes, the name :) The class you mention appears to be part of WPF.

    __________________________________________
    Sergio Pereira
    http://devlicio.us/blogs/sergio_pereira/
  • Re: MVC Form Validation

    12-28-2007, 12:29 PM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    Ok :)

    Thank you for your answers.

    (I personally consider this post as Resolved)

    I wish you a happy new year.
     

  • Re: MVC Form Validation

    01-04-2008, 11:37 AM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    I have some other questions...

    How should I modify the code above if I want to "save" an error for a specific field (for example, the email address) in order to place this specific error besides the Textbox ?  

  • Re: MVC Form Validation

    01-05-2008, 12:52 AM
    • Contributor
      4,382 point Contributor
    • tgmdbm
    • Member since 12-17-2007, 2:08 PM
    • Posts 883
    • ASPInsiders
      TrustedFriends-MVPs

    Simply change AddError(string errorMsg) to AddError(string errorMsg, string property)

    and instead of storing a List<string> store a Dictionary<string, string>

    that way you can associate the error message with the html element and display the message next to it. 

  • Re: MVC Form Validation

    01-05-2008, 6:43 AM
    • Member
      318 point Member
    • dimi3
    • Member since 12-13-2007, 5:02 PM
    • Posts 166

    Thank you tgmdbm for you answer!

    I modified the class from Sergio Pereira as follow:

     

    1    public class ValidationResult
    2 {
    3 public ValidationResult() { }
    4 5 private Dictionary<String, String> messages = new Dictionary<String, String>();
    6 public bool Success { get { return messages.Count == 0; } }
    7
    8 public void AddError(String field, String errorMessage)
    9 {
    10 messages.Add(field, errorMessage);
    11 }
    12
    13 public Dictionary<String, String> GetErrorMessages()
    14 {
    15 return messages;
    16 }
    17 }
     
    Then in the controller, I have:
    1    TempData["validationErrors"] = validationResult.GetErrorMessages();
     
    TempData["validationErrors"] is now a Dictionary<String, String>
     
    How can I access each element in the .aspx view?
    (ViewContext.TempData.SafeGet("validationErrors") is a String)
     
     
  • Re: MVC Form Validation

    01-05-2008, 2:59 PM

    dimi3:
    TempData["validationErrors"] is now a Dictionary<String, String>
    How can I access each element in the .aspx view?
     

    The same way you would iterate any other dictionary:

    <b>Errors:</b><br />
    <ul class="errors">
    <% foreach(string field in ((IDictionary<string,string>)TempData["validationErrors"]).Keys ) { %>
       <li><i><%= field %></i>: <%= ((IDictionary<string,string>)TempData["validationErrors"])[field] %></li>
    <% } %>
    </ul>

    This looks pretty ugly. If I were you I'd create some user control that takes care of this code and put it in the master page, if you have one.

    __________________________________________
    Sergio Pereira
    http://devlicio.us/blogs/sergio_pereira/
  • Re: MVC Form Validation

    01-05-2008, 4:22 PM
    • Contributor
      4,382 point Contributor
    • tgmdbm
    • Member since 12-17-2007, 2:08 PM
    • Posts 883
    • ASPInsiders
      TrustedFriends-MVPs

    I'd have to call bug on this.

    SafeGet should return an object, perhaps a SafeGetString to attempt a ToString() on the object?

    it should be as easy as you think

    <%= Html.TextBox( "fieldName", ViewData.FieldName ) %> <%= ViewContext.TempData.SafeGet("errors")["FieldName"] %>

    But you can always (and probably should) write an extension method to do this.

    public static string Error(this HtmlHelper helper, string fieldName) {
      string s = string.Empty;

      ViewContext.TempData.SafeGet("errors").TryGetValue(fieldName, s);

      return s;

    }

    then it's just 

    <%= Html.TextBox( "fieldName", ViewData.FieldName ) %> <%= Html.Error("FieldName") %>

     

    Filed under:
Page 1 of 2 (27 items) 1 2 Next >