简体   繁体   中英

Require field if checkbox is checked

I have a field in a form that I need to be required if a checkbox in the same form is checked.

There doesn't seem to be a way to do this with regular model validation, so I created a remote validation method in my controller.

The problem is, since the field isn't required always, the validation doesn't even fire if I put it on the field. So I tried putting the validation on the checkbox, and now I get a different problem where the validation doesn't fire when I add text to the field.

Is there a way to do what I'm needing with custom validation, or do I need to do something in JavaScript? If so, what do I need to do?

Form:

<form>
   <input type="checkbox" asp-for="NotRecommended" checked=@Model.NotRecommended /> <label>Not Recommended</label>
   <textarea class="form-control" id="Notes" asp-for="Notes"></textarea>
   <span asp-validation-for="NotRecommended" class="text-danger"></span>
</form>

Model:

public class DetailsViewModel
{
    [DisplayName("Not Recommended")]
    [Remote("RequireNoteForFlag", AdditionalFields = "Notes", ErrorMessage = "Note is required when flagging someone.")]
    public bool NotRecommended { get; set; }

    [DataType(DataType.MultilineText)]
    [MaxLength(1500)]
    [DisplayName("Notes")]
    public string Notes { get; set; }
}

Remote Validator

public IActionResult RequireNoteForFlag(bool NotRecommended, string Notes)
{
    if (NotRecommended && String.IsNullOrWhiteSpace(Notes)) return Json("Note is required when flagging an Assessor");
    else return Json(true);
}

I have implemented this with a custom validator in a similar way. However I applied the annotation to the field that would be required and included a condition in the arguments, eg:

[RequiredIf("NotRecommended = true")]
public string Notes { get; set; }

But, as you may already be aware, there is no way to cross-reference another property in data annotations so you will need to build in the javascript to handle this.

Unobtrusive validation adds a data-val="true" and data-val-required="error message" attribute to the input element so adding this in via javascript when the checkbox is checked will work.

You will also need to reinitialise the form validation so that the inputs with newly applied validation attributes are added.

Joe gave me pretty much the whole answer in the comments, but hasn't posted it as an answer, so I'll post it for anyone else who might need to do this.

Create the Attribute https://github.com/joeaudette/cloudscribe/blob/master/src/cloudscribe.Web.Common/DataAnnotations/RequiredWhenAttribute.cs

Joe's Client-Side Validation https://github.com/cloudscribe/cloudscribe/blob/master/src/cloudscribe.Web.StaticFiles/js/cloudscribe-validation-requiredwhen.js

Modified Client-Side Validation

jQuery.validator.addMethod("requiredwhen", function (value, element, param) {
    var otherPropId = $(element).data('val-other');
    if (otherPropId) {
        var otherProp = $(otherPropId)[0].checked;
        if (otherProp) {
            return element.value.length > 0;
        }
    }
    return true;
});
jQuery.validator.unobtrusive.adapters.addBool("requiredwhen");

View

<input type="checkbox" asp-for="NotRecommended" /> <label asp-for="NotRecommended"></label>
<textarea class="form-control" id="Notes" asp-for="Notes"></textarea>
<span asp-validation-for="NotRecommended" class="text-danger"></span>

Model

[DisplayName("Not Recommended")]
public bool NotRecommended { get; set; }

[DataType(DataType.MultilineText)]
[MaxLength(1500)]
[DisplayName("Notes")]
[RequiredWhen("NotRecommended", true, AllowEmptyStrings = false, ErrorMessage ="A note is required when flagging an Assessor.")]
public string Notes { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM