【问题标题】:Get validation message from JQuery validator从 JQuery 验证器获取验证消息
【发布时间】:2023-04-17 03:39:01
【问题描述】:

使用 MVC、.Net Core 2.1、引导程序、JQuery Unobtrusive Validation... 是否有从 javascript 函数中提取“验证”错误消息的方法?

将此作为我的模型,请注意错误消息:“需要字符串 1”

public class TestObj
{
    [DataType(DataType.Text)]
    [Required(ErrorMessage = "String 1 is required.")]
    public string str1 { get; set; }
    public TestObj() { }
    public TestObj(string i_str)
    {
        this.str1 = i_str;
    }
}

这是我的控制器

    public IActionResult Test()
    {
        TestObj model = new TestObj();
        model = new TestObj("test1");
        return View(model);
    }

这个作为cshtml

<form asp-action="Test" asp-controller="Home" method="post" id="myform">
    <div class="row">
        <div class="col-xs-2" style="width:5em;">
            <input asp-for="@Model.str1" class="form-control small_inp_box" />
        </div>
    </div>
    <div style="clear:both; margin-top:1em;"></div>
    <div asp-validation-summary="All" class="text-danger"></div>
    <div style="clear:both; margin-top:1em;">
        <label id="lbl_msg1"></label>
    </div>
    <input type="submit" name="Submit" class="btn btn-outline-dark" />
</form>

这就是 JavaScript

    <script>
    $(document).ready(function () {
        $("#lbl_msg1").text("Ready");
        $(".small_inp_box:first").focus();
    });
    $(".small_inp_box").focusout(function () {
        if (!$(this).valid()) {
            $(this).addClass("red");
            console.log("invalid!");
            console.log($(this).dataset.valRequired);
        }
        else {
            $(this).removeClass("red");
            console.log("valid!");
        }
    })
</script

我能否从 focusout 函数中获得所需的验证消息“需要字符串 1”?

【问题讨论】:

    标签: jquery asp.net-mvc validation


    【解决方案1】:

    我不确定这是不是最好的方法,但应该可以。将其放入 focusout 函数中:

    var fv = $('#myform').validate();
    
    // setTimeout is needed to let validation to complete
    var currentElement = this;
    setTimeout(function() {
        let error = fv.errorList.filter(function (e) { return e.element == currentElement; })[0];
        console.log(error.message);
    });
    

    【讨论】:

    • AlbertK,我接受了您的回答,并对您的回答投了赞成票。过滤器工作不正确,我仍在审查,但 fv.errorList 是我正在寻找的,谢谢。
    • 这是workable example。看起来过滤器有效。
    • 我将您的原始答案放到了我的页面中,现在它可以完美运行了。不知道我第一次做错了什么,无论如何感谢您的跟进,我以后会更加小心......