-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?
– George Wurthmann
The problem is in your View? how is your View configured? post the example?
– novic