Reputation: 45
Public Class Duration
{
[Required]
Public DurationUnit Unit
[Required]
Public int Length
}
Public Class Employee
{
[RequiredAttribute]
public virtual Duration NotificationLeadTime { get; set; }
}
The fields Unit
and Length
, when not suplied are getting highlighted in Red but the error message is not getting displayed.
I tries also giving [Required(ErrorMessage="sadfdsf")]
,but this is also not working.
I also tried inheriting the class with IValidatableObject
but that also didn't work.
How to display the error message ?
Upvotes: 0
Views: 134
Reputation: 1038730
You should use properties, not fields:
public class Duration
{
[Required]
public DurationUnit Unit { get; set; }
[Required]
public int Length { get; set; }
}
In order to display the corresponding error message use the Html.ValidationMessageFor
helper.
For example:
@Html.EditorFor(x => x.NotificationLeadTime.Unit)
@Html.ValidationMessageFor(x => x.NotificationLeadTime.Unit)
By the way it doesn't really make sense to decorate a non-nullable type such as int
with the [Required]
attribute because those types always have a default value. You should make it a nullable integer instead. Same remark stands for the DurationUnit
property if DurationUnit
is an enum.
Upvotes: 3