There are some ways to do this.
Only with CSS
According to To Microsoft these are the error classes you will have:
- field-validation-error. Defines the output of the Html.Validationmessage method when it’s Displaying an error.
- field-validation-Valid. Defines the output of the Html.Validationmessage method when there is no error.
- input-validation-error. Defines how Elements are rendered when there’s an error. (For example, you can use this class to set the background color of an element to a Different color if its value is invalid. ) This CSS class is used only During client validation (in ASP.NET Web Pages 2).
- input-validation-Valid. Defines the Appearance of Elements
when there is no error.
- validation-Summary-errors. Defines the output of the
Html.Validationsummary method it’s Displaying a list of errors.
- validation-Summary-Valid. Defines the output of the
Html.Validationsummary method when there is no error.
With this, just overwrite the CSS for these classes, in this way:
<style>
.validation-summary-errors {
border:2px solid red;
color:red;
font-weight:bold;
margin:6px;
width:30%;
}
.field-validation-error{
color:red;
font-weight:bold;
background-color:yellow;
}
.input-validation-error{
color:red;
font-weight:bold;
background-color:pink;
}
</style>
Adding a new class to the message
You can add your stylized class to ValidationMessageFor()
, in this way:
@Html.ValidationMessageFor(m=>m.Name, new { @class ="sua-classe-estilizada"})
And in his CSS, you would have your class:
<style>
.sua-classe-estilizada{
color: white;
}
</style>
By Dataannotation
I wouldn’t advise it that way N reasons, but I will demonstrate that it is possible.
If you want to add something via DataAnnotations
, you can do something appreciated with this:
public class EmployeeMetadata
{
[Required]
[Range(1, int.MaxValue,
ErrorMessage = "<img src='/images/error.png' />
Invalid EmployeeID!")]
public int EmployeeID { get; set; }
[Required]
[StringLength(20,
ErrorMessage = "<img src='/images/error.png' />
Invalid first name!")]
public string FirstName { get; set; }
[Required]
[StringLength(20,
ErrorMessage = "<img src='/images/error.png' />
Invalid last name!")]
public string LastName { get; set; }
}
And in his View
would look like this:
@Html.Raw(
HttpUtility.HtmlDecode(
@Html.ValidationMessageFor(m=>m.EmployeeID).ToHtmlString()
))
That way, the result would be this:
Source: binaryintellect
There are other ways, such as returning via Ajax, custom return messages via jQuery, and what your mind imagines, because Razor is "converted" to HTML by "compiling".
How’s your code, especially the view and CSS?
– Maniero