Skip to content

Instantly share code, notes, and snippets.

@Whistler092
Last active May 5, 2021 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Whistler092/8b528cef5e4372c9eea8624a97d0fc29 to your computer and use it in GitHub Desktop.
Save Whistler092/8b528cef5e4372c9eea8624a97d0fc29 to your computer and use it in GitHub Desktop.
Validaciones personalizadas
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using API.Entidades.Validaciones;
namespace API.Entidades
{
public class Genero : IValidatableObject
{
public int Id { get; set; }
[Required(ErrorMessage = "El campo {0} es requerido")]
[StringLength(maximumLength: 10)]
// Validaciones por Propiedad
//[PrimeraLetraMayuscula]
public string Nombre { get; set; }
[Range(18, 120)]
public int Edad { get; set; }
[CreditCard]
public string TarjetaDeCredito { get; set; }
[Url]
public string URL { get; set; }
// Validaciones por Modelo
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!string.IsNullOrEmpty(Nombre))
{
var primeraletra = Nombre[0].ToString();
if (primeraletra != primeraletra.ToUpper())
{
yield return new ValidationResult("La primera letra debe de ser mayúscula", new string[] { nameof(Nombre) });
}
}
}
}
}
using System;
using System.ComponentModel.DataAnnotations;
namespace API.Entidades.Validaciones
{
// Validaciones por Propiedad
public class PrimeraLetraMayusculaAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
return ValidationResult.Success;
}
var primeraLetra = value.ToString()[0].ToString();
if (primeraLetra != primeraLetra.ToUpper())
{
return new ValidationResult("La primera letra debe ser mayúscula");
}
return ValidationResult.Success;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment