views:

429

answers:

1

Hi. Going mad now. I have a MVC solution that i've upgraded from MVC 1 to 2. It all works fine.... except the Validation!

Here's some code:

In the controller:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using MF.Services.Authentication;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MF.Controllers
{
     //basic viewmodel
     public class LogOnViewData
     {
     [Required]
     public string UserName { get; set; }

     [Required]
     public string Password { get; set; }
     }

    [HandleError]
public class AccountController : Controller
{
         [HttpPost]
         public ActionResult LogOn(LogOnViewData lvd, string returnUrl)
         {

         if (ModelState.IsValid)
         {
        //do stuff - IsValid is always true
         }
         }
    }
}

The ModelState is always valid. The model is being populated correctly however. Therefore, if I leave both username and password blank, and post the form the model state is still valid. Argh!

Extra info: using structure map for IoD. Previously, before upgrading to MVC 2 was using the MS data annotation library so had this in my global.asax.cs: ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();

Have removed that now.

I'm sure i'm doing something really basic and wrong. If someone could point it out that would be marvellous. Cheers

A: 

Half way through the development of MVC2, they went from input validation to model validation, which should in all cases validate your object completely. Make sure you're using the latest version (RTM).

However, [Required] merely indicates the attribute must not be null. Unfortunately, String.Empty -which is the default for strings- is not null, so model validation will pass for empty strings.

See this post by Brad Wilson for important details.

As a solution, you could use the [RegularExpression("....")] to impose restrictions on the minimum string length and allowed characters.

mnemosyn
Oh I see - thanks. That does actually make perfect sense :)However, I've started a brand new MVC project which has validation on the login control action that's almost exactly the same as mine. It, of course, works fine. I'm just a bit stumped as to what the difference is!Thanks again
Louzzzzzz
Fixed it! Removed then re-added all the references in my web project and everything works as expected.
Louzzzzzz