вывести ошибку валидации над полем C#
[Desc]
public class Product
{
public enum Category { Toy, Technique, Clothes, Transport}
public int Id { get; set; }
public Category Type { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
public class DescAttribute : ValidationAttribute
{
public DescAttribute()
{
ErrorMessage = "Description text is not valid";
}
public override bool IsValid(object value)
{
Product p = value as Product;
return p is null ||
(p.Description.StartsWith(p.Name) && p.Description != p.Name && p.Description.Length > 2);
}
}
В моём случае если валидация не успешна ошибка выводится вверху страницы 
Как сделать так чтобы эта ошибка валидация выводилась около поля Description ?
Ответы (2 шт):
Автор решения: hekeemje
→ Ссылка
[Remote(action: "VerifyDescription", controller: "Products", AdditionalFields = nameof(Name))]
public string Description { get; set; }
в Контроллере :
[AcceptVerbs("Get", "Post")]
public IActionResult VerifyDescription(string Description, string Name)
{
if (Description.Equals(Name) || !Description.StartsWith(Name))
{
return Json("Description text is not valid.");
}
return Json(true);
}
Автор решения: lancwork
→ Ссылка
Вам нужно переопределить protected override ValidationResult? IsValid(object value, ValidationContext validationContext)
В атрибуте для класса:
protected override ValidationResult? IsValid(object value, ValidationContext validationContext)
{
Product p = value as Product;
if (p is null || (p.Description.StartsWith(p.Name) && p.Description != p.Name && p.Description.Length > 2))
return null;
else
return new ValidationResult(ErrorMessage, new string[] { nameof(p.Description) });
}
Если хотите написать атрибут для свойства, вы можете получить весь объект в validationContext.ObjectInstance чтоб потом обратиться к Name :
protected override ValidationResult? IsValid(object value, ValidationContext validationContext)
{
var product = validationContext.ObjectInstance as Product;
if (product is null)
return null;
var desc = value.ToString();
if (desc.StartsWith(product.Name) && desc != product.Name && desc.Length > 2)
return null;
else
return new ValidationResult(ErrorMessage);
}
И не забудьте в представлении добавить <span asp-validation-for="Description" class="text-danger"></span> чтоб было куда выводить текст валидации.