【发布时间】: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