if condition with required Viewmodel

Asked

Viewed 194 times

1

I wonder if it is possible to use an if for required in a Viewmodel. For example I have these two variables:

 [Required(ErrorMessage = "O campo {0} é obrigatorio.")]
    [Display(Name = "Insc. Estadual")]
    public string InscricaoEstadual { get; set; }
    [Display(Name = "Inscrição Isento")]
    public bool InscricaoIsento { get; set; }

I would like to InscricaoIsento for true when performing Submit, it sends, and if the field InscricaoEstadual and InscricaoIsento is not marked he did the field validation InscricaoEstadual as mandatory, has to do this in a ViewModel ?

  • [Range(typeof(bool), "true", "true", ErrorMessage="O campo inscrição isento precisa ser marcado!")]
public bool InscricaoIsento { get; set; }

  • 1

    You opened this question on 09/24 and it was already answered, I tested it before answering and the validation worked. Then you opened two days ago this: https://answall.com/questions/332973/valida%C3%A7%C3%A3o-required-com-if-viewmodel 1 hour ago you opened this: https://answall.com/questions/333383/validationresult-comdois-par%C3%A2metros.... and now edited that question again :-(...

  • @Renan I’m trying something that works, I don’t know why it’s not working. I even edited the question to be clearer, I opened another one, because I thought the problem wasn’t this validation, so I was trying other ways.

  • @Renan I opened the others, because I was trying otherwise, since this is not working. I’m sorry the confusion.

  • I understand, but when you ask and mark an answer as an answer, your question is associated with that answer and it will serve other people’s doubts as well. But when you edit it days later, it kind of makes sense? Suggestion: Back to the question as it was. Take one of the others you opened, make it very complete, to try to help.

  • @Renan editei está aqui, if you can help me https://answall.com/questions/333383/validationresult-com-dois-par%C3%A2metros Thanks.

  • I edited the answer to be complete, so you can test and see what you were doing wrong that didn’t work for you.

Show 2 more comments

1 answer

2


One option is to do a custom validation.

To create custom validation of your Model need to implement the method Validate of IValidatableObject, within the method Validate you implement your validation logic, thus:

Model:

public class SeuModel : IValidatableObject
{
    //[Required(ErrorMessage = "O campo {0} é obrigatorio.")]
    [Display(Name = "Insc. Estadual")]
    public string InscricaoEstadual { get; set; }

    [Display(Name = "Inscrição Isento")]
    public bool InscricaoIsento { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (InscricaoIsento == false && string.IsNullOrEmpty(InscricaoEstadual))
        {
            yield return new ValidationResult("O campo Insc. Estadual é obrigatorio.");
         }
    }
}

Controller:

public class SeuController : Controller
{
    // GET: Seu
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(SeuModel seuModel)
    {
        return View(seuModel);
    }
}

Index:

@model WebApplication1.Models.SeuModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>SeuModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.InscricaoIsento, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.InscricaoIsento)
                    @Html.ValidationMessageFor(model => model.InscricaoIsento, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.InscricaoEstadual, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.InscricaoEstadual, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.InscricaoEstadual, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Validation:

inserir a descrição da imagem aqui

Browser other questions tagged

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