【发布时间】:2023-01-13 05:05:36
【问题描述】:
我正在 MVC 5 中开发一个项目。有一些表单输入字段,我需要在其中使用 jquery/javascript 进行自定义客户端验证。预期的行为是,例如,当有人试图在电话输入中键入字母或特殊字符时,该字段下方应该显示一个验证错误,或者至少应该触发一个包含错误的警告框。我在脚本文件夹中添加了自定义验证文件。我可以在页面的控制台上看到我写的一些基本日志。我在 js 函数上面临挑战,我们可以在其中捕获字段的 id 并为其提供自定义逻辑。这是我的代码。请建议可以做什么。
@model StudentMVCApp.Models.registration
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm(new
{
@id = "registerFormId",
@class = "form-horizontal",
role = "form"
}))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Register a new student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.firstname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.firstname, new { htmlAttributes = new { @class = "form-control", data_val = "true", data_val_required = "Please dont provide empty name!" } })
@Html.ValidationMessageFor(model => model.firstname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.lastname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.lastname, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.lastname, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.phone, new { htmlAttributes = new { @class = "form-control",@id="phoneid" } })
@Html.ValidationMessageFor(model => model.phone, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/Unobtrusive")
@Scripts.Render("~/CustomValidation")
}
这是我的自定义 JavaScript
console.log("I am working JS");
(function ($) {
console.log("This function is captured");
var phone = $("#phoneid").val();
console.log(phone);
if (phone != null)
console.log(phone);
else if (phone == 100)
alert($(this).val());
else if (phone == "abc")
alert(phone);
else if (phone == abc)
alert(phone)
})(jQuery);
我尝试了不同的教程并尝试了一些 js 函数。但是无法使用该字段的 id 使其工作。
【问题讨论】:
标签: javascript jquery .net asp.net-mvc