自定义验证不触发ASP.NET Core

e37o9pze  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(211)

我正在学习自定义验证属性,并为自己创建了一个简单的示例,但它似乎不起作用。我错过了什么?
这是我的模型

public class Employee
{
    public int? ID { get; set; }

    [MinLength(2)] [Remote(action: "VerifyNameExists",controller:"Employee")]
    public string Name { get; set; }

    [LastNameValid] public string? lastname { get; set; }
    public decimal? Salary { get; set; }

}

字符串
这是我的观点

<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.min.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<a href="~/lib/jquery/dist/jquery.min.map">~/lib/jquery/dist/jquery.min.map</a>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
@model Employee

<div class="container">
    <h1>Create Employee</h1>
    <div class="row">
        <div class="col-sm-8">
            <form class="d-grid form-control-sm" asp-controller="Employee" asp-action="Create" method="post">
                <div class="form-group row">
                    <input class="col-sm-4" asp-for="ID" placeholder="ID" />
                    <span asp-validation-for="ID" style="color:red"></span>
                </div>
                <br />
                <div class="form-group row">
                    <input type="text" class="col-sm-4" asp-for="Name" placeholder="First Name"/>
                    <span asp-validation-for="Name" style="color:red"></span>
                </div>
                <br />
                <div class="form-group row">
                    <input type="text" class="col-sm-4" asp-for=lastname placeholder="Last Name"/>
                    <span asp-validation-for=lastname style="color:red"></span>
                </div>
                <br />
                <br/>
                <input class="btn btn-primary col-sm-4" type="submit" name="Submit" value="Submit" />
            </form>
        </div>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial"></partial>
}


这是我的控制器

public IActionResult Create()
{
    return View();
}
[HttpPost]
public IActionResult Create(Employee emp) 
{
    if (!ModelState.IsValid)
    {
        return View();
    }
    return RedirectToAction("Index",emplist);
}


下面是添加到模型的last name属性的属性类:

using System.ComponentModel.DataAnnotations;

namespace MVCDemo
{
    public class LastNameValidAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (value == "abc")
            {
                return new ValidationResult("not allowed");
            }
            return ValidationResult.Success;
        }
    }
}


我读了这个网站上的其他问题,我不认为我在这里做什么不同。
当我提交表单时,没有根据属性验证姓氏

yfwxisqw

yfwxisqw1#

对于服务器,你可以在if (value == "abc")设置一个断点,你可以看到它为false,试试value.ToString() == "abc"

public class LastNameValidAttribute : ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value.ToString() == "abc")
        {
            return new ValidationResult("not allowed");
        }
        return ValidationResult.Success;
    }
}

字符串
结果:


的数据
对于需要添加js的Client,可以阅读自定义客户端验证了解更多。
下面是一个demo,你可以参考一下:
LastNameValidAttribute:

public class LastNameValidAttribute : ValidationAttribute, IClientModelValidator
{
    public void AddValidation(ClientModelValidationContext context)
    {
        var errorMessage = "not allowed";
        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-lastname", errorMessage);
    }

    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value.ToString() == "abc")
        {
            return new ValidationResult("not allowed");
        }
        return ValidationResult.Success;
    }
    private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }

        attributes.Add(key, value);
        return true;
    }
}


修改js如下:

@section Scripts {
    <partial name="_ValidationScriptsPartial"></partial>
    <script>
        $.validator.addMethod("lastname",
            function (value, element, parameters) {
              
                if (value == "abc") {
                    return false
                }
                else {
                    return true
                }
            });

        $.validator.unobtrusive.adapters.addBool("lastname");
    </script>

}


结果:

相关问题