Condition if with required ViewModel

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 that if InscricaoIsento is true when submitting, it sends, and if the InscricaoEstadual and InscricaoIsento field is not marked it validates the InscricaoEstadual field as required, has how to do this in a ViewModel ?

    
asked by anonymous 24.09.2018 / 14:38

1 answer

2

One option is to do a custom validation.

In order to create custom validation your Model class needs to implement the Validate method of IValidatableObject , within the Validate method you implement your validation logic, like this:

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:

    
24.09.2018 / 16:48