How to provide warnings during validation in ASP.NET MVC?

Solution 1:

Overall Design

To start with, I believe you would have to track somehow if the user choose to ignore the warnings. A simple and transparent way to do that is to have an Ignore Warnings check-box, which user would have to check before submit. Another option is a have them submit the form two times and ignore the warnings on the second submit; then you'd probably need an IgnoreWarnings hidden field. There could be other designs, but for the sake of simplicity I'll go with the first option.

In short, the approach is to create

  • A custom data annotation attribute for all view models supporting the warning type of validation;
  • A known base class which the view models will inherit from;
  • We'll have to duplicate the logic in JavaScript for each custom attribute.

Please note that the code below just illustrates the approach and I have to assume quite a lot of things without knowing the full context.

View Model

In this scenario it's best to separate a view model from an actual model which is a good idea anyway. One possible approach is to have a base class for all view models which support warnings:

public abstract class BaseViewModel
{
    public bool IgnoreWarnings { get; set; }
}

The key reason a model needs to be separate is that there's little sense in storing the IgnoreWarnings property in your database.

Your derived view model will then look as follows:

public class YourViewModel : BaseViewModel
{
    [Required]
    [StringLengthWarning(MaximumLength = 5, ErrorMessage = "Your Warning Message")]
    public string YourProperty { get; set; }
}

StringLengthWarning is a custom data annotation attribute for server and client-side validation. It just supports the maximum length and can easily be extended with any other necessary properties.

Data Annotation Attribute

The core of the attribute is IsValid(value, validationContext method.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class StringLengthWarningAttribute : ValidationAttribute, IClientValidatable 
{
    public int MaximumLength { get; set; }

    public override bool IsValid(object value)
    {
        return true;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var model = validationContext.ObjectInstance as BaseViewModel;
        var str = value as string;
        if (!model.IgnoreWarnings && (string.IsNullOrWhiteSpace(str) || str.Length > MaximumLength))
            return new ValidationResult(ErrorMessage);
        return base.IsValid(value, validationContext);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new StringLengthWarningValidationRule(MaximumLength, ErrorMessage);
    }
}

The attribute implements IClientValidatable and utilizes a custom client validation rule:

public class StringLengthWarningValidationRule : ModelClientValidationRule
{
    public StringLengthWarningValidationRule(int maximumLength, string errorMessage)
    {
        ErrorMessage = errorMessage;
        ValidationType = "stringlengthwarning";
        ValidationParameters.Add("maximumlength", maximumLength);
        ValidationParameters.Add("ignorewarningsfield", "IgnoreWarnings");
    }
}

Client-side JavaScript

Finally, to make it work, you'll need the following JavaScript referenced from your view:

$(function () {
    $.validator.addMethod('stringlengthwarning', function (value, element, params) {
        var maximumlength = params['maximumlength'];
        var ignorewarningsfield = params['ignorewarningsfield'];

        var ctl = $("#" + ignorewarningsfield);
        if (ctl == null || ctl.is(':checked'))
            return true;
        return value.length <= maximumlength;
    });

    $.validator.unobtrusive.adapters.add("stringlengthwarning", ["maximumlength", "ignorewarningsfield"], function (options) {
        var value = {
            maximumlength: options.params.maximumlength,
            ignorewarningsfield: options.params.ignorewarningsfield
        };
        options.rules["stringlengthwarning"] = value;
        if (options.message) {
            options.messages["stringlengthwarning"] = options.message;
        }
    });

}(jQuery));

The JavaScript makes some assumptions you might want to revisit (the check-box name, etc).

UPDATE: HTML Helpers

To display the validation messages separately for errors and warnings, a couple of helpers will be necessary. The following class provides a sample:

public static class  MessageHelpers
{
    public static MvcHtmlString WarningMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (htmlHelper.ViewData.ModelState["IgnoreWarnings"] != null)
            return htmlHelper.ValidationMessageFor(expression);
        return MvcHtmlString.Empty;
    }

    public static MvcHtmlString ErrorMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        if (htmlHelper.ViewData.ModelState["IgnoreWarnings"] == null)
            return htmlHelper.ValidationMessageFor(expression);
        return MvcHtmlString.Empty;
    }
}

In the view they can be used as usual:

        @Html.EditorFor(model => model.YourProperty)
        @Html.ErrorMessageFor(model => model.YourProperty)
        @Html.WarningMessageFor(model => model.YourProperty)

Solution 2:

You could use the depends function of jquery validation to simplify your life.

Ex.

@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)

<label>Ignore Warnings</label>
<input id="ignore-warnings" type="checkbox" />

<script>
  $(function () {
    $("#UserName").rules("add", {
      minlength: {
        param: 6,
        depends: function (element) {
          return !$("#ignore-warnings").attr('checked');
        }
      },

      // server side remote validation for duplicate check
      remote: {
        param: '/account/duplicate',
        depends: function (element) {
          return !$("#ignore-warnings").attr('checked');
        }
      }
    });
  });
</script>

Solution 3:

Just a quick comment on the possible re-submit implementation you mentioned...

For the "did you mean to do this?" validation type, from a user's perspective, having to re-submit a form based off an assumption that they made a mistake could be very annoying. I would only implement this 'pseudo-validation' on the client side with javascript and (hopefully quick) ajax calls if you have to hit the server.

I would also attempt to display the warnings on the input's blur/change events so they show before the user hits submit. Maybe not practical in all situations, but I just thought i'd throw it out there.

Solution 4:

This is just a sketch of a possible solution. There are plenty of examples of adding custom attributes (including above) so I'll skip that bit.

It may be possible to add the use of ignore in the jQuery validator function.

Then use

$("form").validate({  
ignore: ".warning-only"
});

and use the client side validator to add the 'warning-only' class after a first pass through the validator. This should then allow the form to be sent to the server.

As I say, just a sketch, but it is something I have been researching for furture use.