0

I have the following model:

public class Contact
{
    public Contact()
    {
        Name = "Your Name";
        Email = "Your Email";
        Message = "Your Message";
    }

    [Required]
    [StringLength(60,MinimumLength = 3)]
    public string Name { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")]
    public string Email { get; set; }

    [Required]
    [StringLength(2200, MinimumLength = 10)]
    [DataType(DataType.MultilineText)]
    public string Message { get; set; }
}

For Message and Name, their default values (in the constructor) actually pass validation, obviously that is bad. I know I could check for this and throw an error in the Controller, but I'm trying to find a way to do these in the model (as I assume that is the correct place to do it).

Nick Brown
  • 1,167
  • 1
  • 21
  • 38

2 Answers2

2

I wouldn't do this at all server side. Use a textbox watermark ala one of the many methods for ex.

http://code.google.com/p/jquery-watermark/

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Thanks for the suggestion -- I'm actually familiar with watermark and use it all the time. I was simply trying to branch out and learn a bit more about validation - would you consider it not best practice? – Nick Brown Jun 27 '12 at 02:52
  • Client side defaults in a watermark are fine to me, it avoids having to hack around default values in a model which is just that - a hack : ) – Adam Tuliper Jun 27 '12 at 15:57
1

Those look like hints, not default values. You should implement these with javascript, instead of setting them as input values.

Max Toro
  • 28,282
  • 11
  • 76
  • 114
  • Something like setting the value and preventing submit if they match the default values? I had considered that (or just using watermark) but I was trying to get out of my comfort zone and lean more about working with models and validation. If the JS way really is best practice, though, I'll revert back to that. – Nick Brown Jun 27 '12 at 02:56