You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.4 KiB
56 lines
1.4 KiB
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using System.Linq;
|
|
|
|
namespace ex_ValidationWithAttributes
|
|
{
|
|
public class Person : IDataErrorInfo
|
|
{
|
|
public string Name { get; set; }
|
|
|
|
|
|
/// <summary>
|
|
/// Le prénom est requis et doit faire moins de 5 caractères
|
|
/// </summary>
|
|
[Required]
|
|
[MaxLength(5)]
|
|
public string Surname { get; set; }
|
|
|
|
|
|
/// <summary>
|
|
/// L'Age est requis
|
|
/// </summary>
|
|
[Required]
|
|
public int? Age { get; set; }
|
|
|
|
|
|
/// <summary>
|
|
/// Méthode qui permet de chercher tous les attributs et de valider ceux-ci
|
|
/// </summary>
|
|
/// <param name="columnName"></param>
|
|
/// <returns></returns>
|
|
public string this[string columnName]
|
|
{
|
|
get
|
|
{
|
|
|
|
var validationResults = new List<ValidationResult>();
|
|
|
|
if (Validator.TryValidateProperty(
|
|
GetType().GetProperty(columnName).GetValue(this)
|
|
, new ValidationContext(this)
|
|
{
|
|
MemberName = columnName
|
|
}
|
|
, validationResults))
|
|
return null;
|
|
|
|
return validationResults.First().ErrorMessage;
|
|
}
|
|
}
|
|
|
|
public string Error { get; }
|
|
}
|
|
}
|