自定义属性验证:根据所选选项创建所需字段

问题描述 投票:0回答:2

如果从option中选择一个特定的select,我正在尝试创建一个字段。

到目前为止我所拥有的:

视图模型:

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; }
}

CustomAttribute:

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>

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

validator.js

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中的日志)。

大多数谷歌搜索来自实现IClientValidatable界面的ASP.NET MVC并且不是很有用。我正在使用ASP.NET Core 2.2.0。

我确实阅读了微软docs和他们在定制适配器上为不寻常的验证器提供的link

问题:

  1. 如何通过这种方式实现预期的行为?我做错了什么,我该如何解决?
  2. 我还有什么其他选择?我应该使用jQuery Validation Plugin进行单独的客户端验证吗?我不喜欢2个单独的地方进行验证的想法。
  3. 有人可以向我解释为什么javascript函数中的console.log()s永远不会被执行?我有FromDateToDate的自定义验证器,它们在那里执行。唯一的区别是我使用jQuery.validator.unobtrusive.adapters.addBool而不是jQuery.validator.unobtrusive.adapters.add
javascript c# jquery asp.net-core-mvc unobtrusive-validation
2个回答
0
投票

您可以让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" });
        }
    }

使用pattern matching可以使上面的语法更加优雅

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


0
投票

comment部分在form之外,所以验证永远不会发生。答案是在原帖中的link中找到的。

重要说明:jQuery Validate要求您的输入元素位于<form>元素内以便进行验证。

© www.soinside.com 2019 - 2024. All rights reserved.