Validation with more Net Core MVC fields?

Asked

Viewed 168 times

-1

I need to validate on a form made in ASPNet Core MVC, but in this validation I need to use more than one field, example below:

Models:

public class Fornecedor
{
    public virtual int ID { get; set; }
    public virtual DateTime DtNascimento { get; set; }
    public virtual Empresa Empresa{get; set;}
}

public class Empresa
{
    public virtual int ID { get; set; }
    public virtual string Uf { get; set; }
    public virtual IList<Fornecedor> ListaFornecedor { get; set; }
}

I need to create a Validation in the Supplier class that is made only if the company’s UF attribute is of a certain value, I tried to use a CustomValidation, sort of like this:

protected override ValidationResult IsValid(
    object value, 
    ValidationContext validationContext
)
{
    var fornecedor = (Models.Fornecedor) validationContext.ObjectInstance;

    if (fornecedor.Empresa.Uf == "PR")
    {
        if (Utils.GetAge(value) < 18)
        {    
            return 
                new ValidationResult
                ("Para o Paraná, são aceitos apenas fornecedores maiores de idade.");
        }
    }
    return ValidationResult.Success;
}

The Company object is always null, man controller is like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IFormCollection form, Fornecedor fornecedor)
{
    try
    {
        int idEmpresa = int.Parse(form["Empresa"].ToString());
        fornecedor.Empresa = _session.Get<Empresa>(idEmpresa);
        fornecedor.DtHoraCadastro = System.DateTime.Now;
        var ListaEmpresa = _session.Query<Empresa>().ToList();
        ViewBag.ListaEmpresa = ListaEmpresa;

        if (ModelState.IsValid)
        {
            _session.Save(fornecedor);

            return RedirectToAction(nameof(Index));
        }
        return View();
    }
    catch
    {
        return View();
    }
}

I’ve searched several places but all examples are done using multiple attributes within the same class and not using attributes within an object within the main class.

  • How is the input of the fields related to the Company in your View?

  • The problem is in your View? how is your View configured? post the example?

1 answer

0

The problem is that your Customvalidation occurs when the object is mapped by the application and passed to Action and at this time Company is null. In this case, you’d better use Action Filters. Create a Filter for your Action:

    namespace ActionFilters.Filters
{
    public class ActionFilterExample : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // our code before action executes
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // our code after action executes
        }
    }
}

Do the denpendence injection:

services.AddScoped<ActionFilterExample>();

And then make your implementation according to what you need:

namespace ActionFilters.Filters
    {
        public class ActionFilterExample : IActionFilter
        {
            private readonly IEmpresaService _service;

            public ActionFilterExample(IEmpresaService empresaSservice)
            {
                _service = empresaSservice;
            }

            public void OnActionExecuting(ActionExecutingContext context)
            {
                var fornecedor = context.ActionArguments.SingleOrDefault(p => p.Value is Fornecedor) is Fornecedor;
                if(fornecedor != null)
                {
                    fornecedor.Empresa = _service.GetById(idEmpresa); //Utilize o seu serviço para buscar a empresa
                    if (fornecedor.Empresa.Uf == "PR")
                    {
                        if (Utils.GetAge(value) < 18)
                        {

                            context.Result = new BadRequestObjectResult("Para o Paraná, são aceitos apenas fornecedores maiores de idade.");
                            return;

                        }
                    }
                }
            }

            public void OnActionExecuted(ActionExecutedContext context)
            {
                // our code after action executes
            }
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.