How to provide warnings during validation in ASP.NET MVC?
Posted
by
Alex
on Stack Overflow
See other posts from Stack Overflow
or by Alex
Published on 2012-11-10T05:46:42Z
Indexed on
2012/11/14
5:00 UTC
Read the original article
Hit count: 171
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 theDescription
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?
© Stack Overflow or respective owner