ValidationResult with two parameters

0

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?

    
asked by anonymous 01.10.2018 / 14:05

2 answers

1

To use this other form of validation (via CustomValidation ) you create your own validation attribute for the property you choose.

In your case above, you have chosen the InscriptionType property, stating that the validation will occur via the Validate method of the Validation class and by adding the attribute below in this property: [CustomValidation(typeof(Validacao), "ValidarInscricao")] .

In order not to give an error, you need to remove the second parameter from the ValidarInscricao method:

    public class Validacao
    {
        public static ValidationResult ValidarInscricao(string inscricao /*, bool isento*/)
        {
            /*
                Aqui você validaria algo específico só da Inscrição Estatual....
            */

            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.");
        }
    }

But,insteadofvalidatingaproperty,youwanttovalidatetwopropertiesatthesametime,Ibelievethatthiswillanswer:#

  •     
  • 02.10.2018 / 14:56
    0
    public static class DataAnnotationsValidatorExtension
    {
        public static bool Validate<T>(T instance, out List<ValidationResult> validationResults) where T : class
        {
            validationResults = new List<ValidationResult>();
            var validationContext = new ValidationContext(instance, null, null);
            return Validator.TryValidateObject(instance, validationContext, validationResults, true);
        }
    }
    

    Example usage:

                var errors = new List<ValidationResult>();
                var minhaInstanciaClasse = new MinhaClasse();
            DataAnnotationsValidatorExtension.Validate(minhaInstanciaClasse , out errors);
    
        
    01.10.2018 / 14:23