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 :)

5
  • 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" Commented Jul 29, 2013 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: 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. Commented Mar 10, 2015 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 =) Commented Mar 11, 2015 at 6: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". Commented Mar 11, 2015 at 21:53
  • stackoverflow.com/questions/53042131/… Commented Oct 24, 2019 at 14:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.