Where can I change the color of this ErrorMessage
?
There are some ways to do this.
Second Microsoft are the classes of errors you will have:
So, you just need to override CSS for these classes, like this:
<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>
You can add your stylized class to ValidationMessageFor()
, like this:
@Html.ValidationMessageFor(m=>m.Name, new { @class ="sua-classe-estilizada"})
And in your CSS , you would have your class:
<style>
.sua-classe-estilizada{
color: white;
}
</style>
I do not recommend this form for N reasons, but I will demonstrate that it is possible.
If you want to add something via DataAnnotations
, you can do something cool with it:
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 your 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 return via Ajax, custom return messages via jQuery, and what your mind envisions, as Razor is "converted" to HTML when compiling.
Normally you change this in CSS (usually found in ~/Content/css
). See the styles:
.field-validation-error
- directly what you want .input-validation-error
- auxiliary if you want to modify the field itself when error .validation-summary-errors
- used if there is a separate error summary They all have a counterpart to the valid state that can be used as well. In general it should be in the normal state or hide the error information.
You can do it in view , but it is not usually the best way, unless you have some specific condition that can not be used in CSS:
@Html.ValidationMessageFor(m => m.Restaurante, "", new { @style = "color : yellow" })
It does not make sense to put in the annotation. Every thing in its place. You can use inline HTML / CSS. But for what? In the view conditionally it is understandable, although I can not see much utility (I see any), but putting something that is fixed in the application goes against the technology you are using. Switching to external CSS is even more flexible.
If you want to insist, it would be something like this:
[ErrorMessage = "<p style = 'color : blue;'>Preencha o nome do restaurante</p>")]