Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8895087
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T23:40:50+00:00 2026-06-14T23:40:50+00:00

Sometimes user input is not strictly invalid but can be considered problematic. For example:

  • 0

Sometimes user input is not strictly invalid but can be considered problematic.

For example:

  • A user enters a long sentence in a single-line Name field. He probably should
    have used the Description field instead
    .
  • A user enters a Name that is very similar to that of an existing entity. Perhaps he’s inputting the same entity but didn’t realize it already exists, or some concurrent user has just entered it.

Some of these can easily be checked client-side, some require server-side checks.

What’s the best way, perhaps something similar to DataAnnotations validation, to provide warnings to the user in such cases? The key here is that the user has to be able to override the warning and still submit the form (or re-submit the form, depending on the implementation).

The most viable solution that comes to mind is to create some attribute, similar to a CustomValidationAttribute, that may make an AJAX call and would display some warning text but doesn’t affect the ModelState. The intended usage is this:

[WarningOnFieldLength(MaxLength = 150)]
[WarningOnPossibleDuplicate()]
public string Name { get; set; }

In the view:

@Html.EditorFor(model => model.Name)
@Html.WarningMessageFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)

So, any ideas?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T23:40:51+00:00Added an answer on June 14, 2026 at 11:40 pm

    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)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'd like to take user input (sometimes this will be large paragraphs) and generate
I'm creating a dynamic datatable full of input fields. Sometimes when user insert values
I have a field that a user can input first and last name to
Sometimes in Salesforce tests you need to create User objects to run part of
Sometimes data is deleted from a database by a user which has been referred
Sometimes I m getting unicode errors like below in my django site when user
I have a user of my application that sometimes when they run the application
I have an each method that is run on some user-submitted data. Sometimes it
I see that when connecting services to twitter/facebook, sometimes apps are storing the user
I have a website, which will be frequently updated. Sometimes changes happen to User

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.