Call an attribute from one class to another to make a ValidationResult

2

I am looking for ways to validate my model with entity framework , and with validationResult I can achieve it, but with only one class, what do you propose to call another class and validate? an attribute of that kind?

Example:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
        {
             if (ValorFacturado < (VozCargoAdicional + DatosCargoAdicional + OtrosCargosAdicional + CargoReposicionArmetales + CargoReposicionUsuario))
            {
                yield return new ValidationResult("Valor facturado es menor", new[] { "El valor es mayor que factura" });
        }

To this sum I must add a field that is in another model.

    
asked by Drz 22.11.2016 в 17:52
source

2 answers

1

I think your problem is that you have not defined your model well. A model in Asp.NET MVC can be composed of several models in turn. The concepts of entity and model in this architecture do not have to coincide. You can have a Client entity for example with 25 properties, but then the CustomerModel of your View can contain 5 of those fields. In short, a model in my view, is a projection of one or more entities. You can create your model so you can solve your problem

public class MiModeloCompuesto
{
     public MiModelo1 Modelo1 { get; set; }
     public MiModelo2 Modelo2 { get; set; }
}

Then with this example you can implement the validation of MyCompositeModel and access the properties of Model1 and Model2. I hope you have made me understand. Greetings

    
answered by 26.11.2016 / 16:54
source
2

Hello, a way to validate data in your business entity, one option would be to use Fluent Validation

JeremySkinner / FluentValidation

Here you have an example code

public class ProductoValidator : AbstractValidator<Producto>
{
    public ProductoValidator()
    {
        CascadeMode = CascadeMode.Continue;
        RuleFor(x => x.Nombre)
            .NotEmpty().WithMessage("El Nombre no puede estar vacío")
            .Must(x => x.Length > 3).WithMessage("El Nombre, debe tener mas de tres caracteres")
            .Must(x => x.Length < 81).WithMessage("El Nombre, debe tener menos de 81 caracteres");

        RuleFor(x => x.CategoriaId)
            .NotNull().WithMessage("Favor de asignar un elemento")
            .NotEqual(0).WithMessage("Debe seleccionar Categoría");

        RuleFor(x => x.LineaId)
            .NotNull().WithMessage("Favor de asignar un elemento")
            .NotEqual(0).WithMessage("Debe seleccionar la Linea");

        RuleFor(x => x.ModeloId)
            .NotNull().WithMessage("Favor de asignar un elemento")
            .NotEqual(0).WithMessage("Debe seleccionar un Modelo");

        RuleFor(x => x.MarcaId)
            .NotEqual(0).WithMessage("Debe seleccionar una Marca")
            .NotNull().WithMessage("Favor de asignar un elemento");

    }
}

Another example

public class ProveedorValidator : AbstractValidator<Proveedor>
{
    public ProveedorValidator()
    {
        // Indicamos que la validación continue aún y cuando una de ellas falle.
        CascadeMode = CascadeMode.Continue;
        RuleFor(x => x.RazonSocial)
            .NotEmpty().WithMessage("La Razón Social no puede estar vacía")
            .Must(x => x.Length > 3).WithMessage("La Razón Social, debe tener mas de tres caracteres")
            .Must(x => x.Length < 81).WithMessage("La Razón Social, debe tener menos de 81 caracteres");

        RuleFor(x => x.DocumentoIdentidad)
            .NotNull().WithMessage("Favor de asignar un elemento")
            .NotEqual((EnumDocumentoEdentidad)Convert.ToInt32(-1)).WithMessage("Debe seleccionar Documento de Identidad");

        When(x => x.DocumentoIdentidad == EnumDocumentoEdentidad.DNI, () =>
          {
              RuleFor(x => x.NroDocumento)
              .NotNull()
              .NotEmpty().WithMessage("El Nro. de DNI, no puede estar vacía")
              .Length(8).WithMessage("El Nro. de DNI, debe de tener una longitud de '8' caracteres")
              .Must(x => x != "11111111" && x != "22222222"
                         && x != "33333333" && x != "44444444"
                         && x != "55555555" && x != "66666666"
                         && x != "77777777" && x != "88888888"
                         && x != "99999999").WithMessage("El Nro. DNI, no tiene un formato valido");
          });

        When(x => x.DocumentoIdentidad == EnumDocumentoEdentidad.RUC, () =>
        {
            RuleFor(x => x.NroDocumento)
            .NotNull()
            .NotEmpty().WithMessage("El Nro. de RUC, no puede estar vacía")
            .Length(11).WithMessage("El Nro. de RUC, debe de tener una longitud de '11' caracteres")
            .Must(x => x != "11111111111" && x != "22222222222"
                       && x != "33333333333" && x != "44444444444"
                       && x != "55555555555" && x != "66666666666"
                       && x != "77777777777" && x != "88888888888"
                       && x != "99999999").WithMessage("El Nro. RUC, no tiene un formato valido");
        });
    }
}

You can adapt it to your needs.

    
answered by 22.11.2016 в 20:07