views:

1051

answers:

1

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?

+2  A: 

Two options:

(1) You can make a Projecten viewModel where all fields are strings. This way the viewModel will always be created from the posted data and your dataannotations validation will always be evaluated. Obviously, you would then map the viewModel to your properly typed business objects maybe using AutoMapper.

(2) You can subclass the model binder.

zaph0d
I ended up using the Autobinder and created a viewmodel which contains just strings for the int's and datetimes. then i use the validator of data-annotations which i used for Projecten on the new viewmodel. after all of that i just parsed it back to the Projecten object and submit it. Did take me some time to figure it all out though :)
Stefanvds