简体   繁体   English

如果选中了复选框,则为必填字段

[英]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? 是否可以通过自定义验证来完成我需要做的事情,还是需要在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. 但是,您可能已经知道,无法在数据注释中交叉引用另一个属性,因此您将需要内置javascript来处理此问题。

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. 非侵入式验证会向输入元素添加data-val =“ true”和data-val-required =“错误消息”属性,因此在选中复选框时通过javascript添加此属性即可。

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 创建属性 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 Joe的客户端验证 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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