Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4 MVC 2 Validation with annotations warning instead of error

I am using .NET 4 with MVC 2 for validating with Annotations. Is there a (simple) solution for giving back a warning instead of the error? So that I am able to get a green or yellow box with a message like "you should not use this content, but you may".

Big thanks in advance! :)

EDIT:
Please observe that I am already able to throw out errors via ErrorMessage but I additionally want something like WarningMessage or InfoMessage so that the user only gets a warning but might proceed. Is there a solution for this?

The Pseudocode would be: (Please note the "pseudo", because WarningMessage is (unfortunately) not a valid class)

public class Person
{
  [StringLength(50)]
  [Required(ErrorMessage = "You MUST enter a name!")]
  public string Name { get; set; }

  [Required(WarningMessage = "It is recommended to fill out the age but you may leave it out)]
  public int Age { get; set; }
}

And yes I want to have this centrallized in my validation class - not somewhere in a .js-file.

like image 322
Jaques le Fraque Avatar asked Jun 18 '11 11:06

Jaques le Fraque


People also ask

Can we do validation in MVC using data annotations?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.

Which of the following are alternatives to perform model validation instead of using built in validation attributes?

Alternatives to built-in attributes If you need validation not provided by built-in attributes, you can: Create custom attributes. Implement IValidatableObject.

How do you validate model data using DataAnnotations attributes?

ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.

How does ValidationMessageFor work in MVC?

ASP.NET MVC: ValidationMessageFor ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. Visit MSDN to know all the overloads of ValidationMessageFor() method.


2 Answers

I will first quickly comment that I'm not sure if this is a good idea!

"Required" attribute has a certain "character" - people expect certain things of it when they include this on their attributes. If you want to use attributes to define this behaviour, try to describe what you're doing more exactly, so instead of your:

[Required(WarningMessage = "It is recommended to fill out age...")]
public int Age { get; set; }

I'd have:

[PreSubmitWarningMessage("It is recommended to fill out age...")]
public int Age { get; set; }

You can create your own attributes that'll affect how the request is handled, though this won't propagate to client-side validation like the standard MVC attributes do.

To get this to play nice with MVC, you need to create this as an Action Filter - specifically by implementing the ActionFilterAttribute and overriding the OnActionExecuted method:

public class PreSubmitWarningMessage : ActionFilterAttribute
{    
    private string _warningMessage;

    public PreSubmitWarningMessage(string warningMessage)
    {
        _warningMessage = warningMessage;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // stuff you do here will happen before the 
        // controller action is executed.

        // you can compare the private warning message 
        // to the metadata in filterContext
    }
}

You could do a couple of things in here, I'm not sure what best practice would be, but at the hackiest, you have access to the model in filterContext, so you can change the behaviour of your controller action, updating your view model to a certain state if your warning condition (for this case, that the field is required).

People might make a case for just extending the RequiredAttribute, but I don't think it's correct to say that your new Attribute IS a RequiredAttribute, so inheritence wouldn't be conceptually correct.

like image 59
simple Avatar answered Nov 15 '22 11:11

simple


I'm not sure how this would even work. If the user doesn't enter the data, and the data is accepted, then you would go on to some other page and they would never see the warning message. This would mean you would either have to not progress, showing them the warning (and then requiring them to do something else to progress) or you would have to pop up a dialog or alert requiring them to approve going on.

Neither is a very good solution from a usability standpoint.

How do you propose the user actually see the warning?

like image 45
Erik Funkenbusch Avatar answered Nov 15 '22 11:11

Erik Funkenbusch