自定义属性验证:基于选定选项所需的字段



我正在尝试制作一个需要的字段,如果从 select选择了特定的 option

到目前为止我拥有的东西:

ViewModel:

public enum RequestType
{
    PaidLeaveOfAbsence = 1,
    WorkFromHome = 2,
    SickLeave = 3,
    BriefLeaveOfAbsence = 4
}
public class RequestFormViewModel
{
    public RequestType SelectedRequestType { get; set; }
    public DateTime FromDate { get; set; }
    public DateTime ToDate { get; set; }
    [RequieredIf("SelectedRequestType")]
    public string Comment { get; set; }
}

自定义:

public class RequieredIfAttribute : ValidationAttribute, IClientModelValidator
{
    private readonly string _otherProperty;
    public RequieredIfAttribute(string otherProperty)
    {
        _otherProperty = otherProperty;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string comment = (string)value;
        RequestType selectedRequestType = (RequestType)validationContext.ObjectType.GetProperty(_otherProperty).GetValue(validationContext.ObjectInstance, null);
        if (string.IsNullOrEmpty(comment) && selectedRequestType == RequestType.BriefLeaveOfAbsence)
        {
            return new ValidationResult("Comment is requiered.");
        }
        return ValidationResult.Success;
    }
    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-required-if", "Comment is requiered.");
        MergeAttribute(context.Attributes, "data-val-other", "#" + _otherProperty);
    }
    private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
}

html:

<div class="row">
<div class="col-0 col-md-2"></div>
<div class="col-12 col-md-4">
    <form asp-action="Create">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="SelectedRequestType" class="control-label"></label>
            <select asp-for="SelectedRequestType" asp-items="Html.GetEnumSelectList<RequestType>()" class="form-control">
                <option selected="selected" value="">Select a request</option>
            </select>
            <span asp-validation-for="SelectedRequestType" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="FromDate" class="control-label"></label>
            <input asp-for="FromDate" class="form-control" type="text" value="" id="fromDate" autocomplete="off" />
            <span asp-validation-for="FromDate" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="ToDate" class="control-label"></label>
            <input asp-for="ToDate" class="form-control" type="text" value="" id="toDate" autocomplete="off" />
            <span asp-validation-for="ToDate" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
</div>
<div class="col-12 col-md-4">
    <div class="form-group">
        <label asp-for="Comment" class="control-label">Comment</label>
        <textarea asp-for="Comment" class="form-control" id="comment" rows="3"></textarea>
        <span asp-validation-for="Comment" class="text-danger"></span>
    </div>
</div>
<div class="col-0 col-md-2"></div>

生成的html:

<select class="form-control" data-val="true" id="SelectedRequestType" name="SelectedRequestType">
    <option selected="selected" value="">Select a request</option>
    <option value="1">PaidLeaveOfAbsence</option>
    <option value="2">WorkFromHom</option>
    <option value="3">SickLeave</option>
    <option value="4">BriefLeaveOfAbsence</option>
</select>
...
<div class="form-group">
    <label class="control-label" for="Comment">Comment</label>
    <textarea class="form-control" id="comment" rows="3" data-val="true" data-val-other="#SelectedRequestType" data-val-required-if="Comment is required." name="Comment"></textarea>
    <span class="text-danger field-validation-valid" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>

服务器端验证正常。我一直坚持添加客户端验证,到目前为止,我都有:

验证器

jQuery.validator.addMethod("required-if",
    function (value, element, param) {
        var otherProp = $($(element).data('val-other'));
        console.log(otherProp);
        if (!value.trim() && otherProp.val() == 4) {
            return false;
        }
        return true;
    }
)
jQuery.validator.unobtrusive.adapters.add("required-if", ["other"], 
    function (options) {
        console.log(options);
        options.rules["required-if"] = "#" + options.params.other;
        options.messages["required-if"] = options.message;
});

我已经放了一些console.log() S,但是它们从未执行。(我确实将日志保存在Chrome中)。

大多数Google搜索来自实现IClientValidatable接口的ASP.NET MVC,并且不是很有用。我正在使用asp.net core 2.2.0。

我确实阅读了Microsoft文档及其在自定义适配器上为不寻常验证器提供的链接。

问题:

  1. 如何通过这种方式实现预期行为?我在做什么错,我该如何解决?

  2. 我的其他选择是什么?我应该只使用jQuery验证插件进行单独的客户端验证?我不喜欢2个单独验证位置的想法。

  3. 有人可以向我解释为什么JavaScript功能中的console.log() S从未执行?我有FromDateToDate的自定义验证器,并且在那里执行。唯一的区别是我使用 jQuery.validator.unobtrusive.adapters.addBool代替jQuery.validator.unobtrusive.adapters.add

您可以使您的FormViewModel扩展了IvalidatableObject。完成该实施验证方法后。您可以根据模型中的值进行自定义验证。类似:

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(SelectedRequestType == RequestType.PaidLeaveOfAbsence) 
        {
            // Check if field is not null and return
            yield return new ValidationResult(
            "SomeField should be present.",
            new[] { "SomeField" });
        }
    }

您可以通过使用图案匹配

使上述语法更优雅

您可以在此链接上找到有关模型验证的更多信息

comment部分在form之外,因此验证永远不会发生。答案是在我的原始帖子中的链接中找到的。

重要说明:jQuery validate需要您的输入元素为 为了验证<form>元素的内部。

最新更新