1

I have a problem with the Required attribute in MVC. I have a field with a default value "Name". When I submit the form, MVC validates the field. If the field is empty, the required message appears. The problem is, that the error message do not appear because of the default value.

Is it possible, that the ErrorMessage also appears when the field has the default value "Name".

Sorry for my bad english :)

tereško
  • 58,060
  • 25
  • 98
  • 150
proud
  • 53
  • 2
  • 8
  • 1
    Please, stop referring to "ASP.NET MVC" simply as "MVC". One is a framework, while other is a language-independent design pattern. It's like calling IE - "the internet" – tereško Jul 29 '13 at 23:15
  • @tereško I could similarly ask, "Please stop referring Internet Explorer simply as 'IE'. One is an internet browser while the others are: http://en.wikipedia.org/wiki/Ie ." My point being, we all abbreviate. Get Microsoft to rename the framework if you really want to do us a favor. – xr280xr Mar 10 '15 at 21:30
  • @xr280xr you fail. Because you are trying to imply that "MVC" is abbreviation of "ASP.NET MVC framework" ... which it is not =) – tereško Mar 11 '15 at 06:36
  • @tereško Reading the OP, it's obvious what proud was talking about, but looking at your edit history on the tags, I see where you're coming from on your 1st comment. But you should still check out the definition of "abbreviate". – xr280xr Mar 11 '15 at 21:53
  • https://stackoverflow.com/questions/53042131/how-to-override-default-required-error-message/58543227#58543227 – VCody Oct 24 '19 at 14:11

1 Answers1

4

I will suggest two ways of dealing with this.

First, you can create a custom validation attribute, an example of which can be found [here].1

Here's a rough and ready example:

public class ValidateDefaultValueAttribute : ValidationAttribute {
    protected override ValidationResult IsValid (object value, ValidationContext validationContext) {
        string value = value.ToString();

        if (value == "Name")
            return new ValidationResult("Please enter a different name.");

        return ValidationResult.Success;
    }
}

Or, it sounds like you want to display a 'Name' in an input field? If you're using HTML 5 then try the placeholder attribute e.g.

<input type="text" placeholder="Name">

That will display the word 'Name' in the field but is overridden once the user starts typing in the field.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • Great advice. i would change the `ValidateDefaultValueAttribute` to receive the `value` (default name in this case) in the constructor (`[ValidateDefaultValueAttribute(Value="Name")]`), so it can be used in a more generic way for any field that rejects some default value. – haim770 Jul 17 '13 at 07:32