Validate MVC 2 form using Data annotations and Linq-to-SQL, before the model binder kicks in (with D

Posted by Stefanvds on Stack Overflow See other posts from Stack Overflow or by Stefanvds
Published on 2010-02-18T11:15:30Z Indexed on 2010/04/03 6:43 UTC
Read the original article Hit count: 671

I'm using linq to SQL and MVC2 with data annotations and I'm having some problems on validation of some types.

For example:

[DisplayName("Geplande sessies")]
[PositiefGeheelGetal(ErrorMessage = "Ongeldige ingave. Positief geheel getal verwacht")]
public string Proj_GeplandeSessies { get; set; }

This is an integer, and I'm validating to get a positive number from the form.

public class PositiefGeheelGetalAttribute : RegularExpressionAttribute {
    public PositiefGeheelGetalAttribute() : base(@"\d{1,7}") { }
}

Now the problem is that when I write text in the input, I don't get to see THIS error, but I get the errormessage from the modelbinder saying "The value 'Tomorrow' is not valid for Geplande sessies."

The code in the controller:

[HttpPost]
public ActionResult Create(Projecten p)
{
    if (ModelState.IsValid)
    {
        _db.Projectens.InsertOnSubmit(p);
        _db.SubmitChanges();

        return RedirectToAction("Index");
    }
    else
    {
        SelectList s = new SelectList(_db.Verbonds, "Verb_ID", "Verb_Naam");
        ViewData["Verbonden"] = s;
    }

    return View();
}

What I want is being able to run the Data Annotations before the Model binder, but that sounds pretty much impossible. What I really want is that my self-written error messages show up on the screen.

I have the same problem with a DateTime, which i want the users to write in the specific form 'dd/MM/yyyy' and i have a regex for that. but again, by the time the data-annotations do their job, all i get is a DateTime Object, and not the original string. So if the input is not a date, the regex does not even run, cos the data annotations just get a null, cos the model binder couldn't make it to a DateTime.

Does anyone have an idea how to make this work?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-mvc-2