Last active
May 5, 2021 20:11
-
-
Save Whistler092/8b528cef5e4372c9eea8624a97d0fc29 to your computer and use it in GitHub Desktop.
Validaciones personalizadas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) }); | |
} | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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