Validationresult with two parameters

Asked

Viewed 305 times

0

I am trying to use custom validation as explained in this link, but then 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 as true the Exempt Registration.

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 don’t know how to pass the parameters to the function.

Edit I also tried to do it this way: This 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 is the message not working? Here’s how I put in the 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 don’t know if there’s anything missing, but he doesn’t do the validation. 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 controller function to do the validation, before returning the error. There is no way this validation can be done only in the client, without the need to enter the controller?

  • Pass a class as a parameter instead of multiple parameters, it’s an elegant solution and you already implement SOLID

  • @Jeangatto did not understand, have some example to help me ? o ValidationResult agrees to pass the class ?

  • Are you using the Fluentvalidation or the validation of Dataannotations? I usually use Fluentvalidation, it’s very flexible, https://github.com/JeremySkinner/FluentValidation

  • Look at the documentation here, it’s very easy! https://fluentvalidation.net/start

  • @Jeangatto I’m using the DataAnnotations

  • @Jeangatto I’m trying to use the FluentValidation, but how do I validate two fields together ?

  • there is already a very similar answer to your question https://answall.com/a/283166/43340

Show 2 more comments

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 Subscribed status property, stating that the validation will take place via the Validate class description method and adding the attribute below to this property: [CustomValidation(typeof(Validacao), "ValidarInscricao")].

To avoid error, you need to remove the second parameter from the method ValidarInscricao:

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

inserir a descrição da imagem aqui

But, as opposed to validating a property, you want to validate two properties at the same time, I believe that this way meets: if condition with required Viewmodel

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 of use:

            var errors = new List<ValidationResult>();
            var minhaInstanciaClasse = new MinhaClasse();
        DataAnnotationsValidatorExtension.Validate(minhaInstanciaClasse , out errors);
  • Sorry I did not understand very well, I edited the question with the way I tried to do, but still does not appear the return message.

Browser other questions tagged

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