I'm trying to use custom validation, as explained in this link , but there I can only pass one parameter to validate, and I need both, because if the field is empty and the other is false, it has to either fill in the State Registration field or mark true
Exempt Subscription.
I wanted something like:
public class Validacao
{
public static ValidationResult ValidarInscricao(string inscricao, bool isento)
{
bool ehValido;
if (inscricao == null && isento == false)
{
ehValido = false;
}
else { ehValido = true; }
if (ehValido)
return ValidationResult.Success;
else
return new ValidationResult("A inscrição não é valido.");
}
}
[Display(Name = "Inscrição Isento")]
public bool InscricaoIsento { get; set; }
[CustomValidation(typeof(Validacao), "ValidarInscricao")]
[Display(Name = "Insc. Estadual")]
public string InscricaoEstadual { get; set; }
But I do not know how to pass parameters to the function.
Edit I also tried to do this: Here is my HTML:
<label asp-for="InscricaoEstadual" class="col-md-2 control-label" style="text-align:left;"></label>
<div class="col-md-3">
<input asp-for="InscricaoEstadual" class="form-control" type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57">
<span asp-validation-for="InscricaoEstadual" class="text-danger"></span>
<input asp-for="InscricaoIsento" type="checkbox" />
<label asp-for="InscricaoIsento" class="control-label"></label>
<span asp-validation-for="InscricaoIsento" class="text-danger"></span>
</div>
Why the message is not working? Here's how I put it in class
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (InscricaoIsento == false && string.IsNullOrEmpty(InscricaoEstadual))
{
yield return new ValidationResult("O campo Insc. Estadual é obrigatorio.", new string[] { "InscricaoEstadual" });
}
}
I do not know if something is missing, but it does not validate. It enters the condition, it just does not appear the message, it returns the following error:
NullReferenceException: Object reference not set to an instance of an object.
I checked that it enters the function of the controller to do the validation, before it returns the error. Can not this validation be done only on the client, without the need to enter the controller?