【问题标题】:Custom Client Side Validation through JavaScript通过 JavaScript 自定义客户端验证
【发布时间】: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


    【解决方案1】:

    您需要将上面的代码附加到事件中,例如输入或提交。 现在它只在页面加载时运行一次

    就像是

    $(function() {
      console.log("This function is captured");
      const $phone = $('#phoneid');
      $phone.on('input',function() {
        const val = $(this).val(); // get the value - it is a string
        console.log(val);
        if (val == 100) console.log('100'); // note the == coerces the numeric string to number
        else if (phone == 'abc') console.log('abc');
      });
    });
    

    【讨论】:

      【解决方案2】:

      我建议在您的视图中使用 jquery.validation.unobstrusive 包脚本:

      <script src="~/Scripts/Jquery/jquery-1.9.1.js"></script>
      <script src="~/Scripts/Jquery/jquery.validate.js"></script>
      <script src="~/Scripts/Jquery/jquery.validate.unobtrusive.js"></script>
      

      并通过编写 jquery 在表单元素上添加您自己的自定义验证,例如:

      $("#myinput").rules("add", {
        required: true,
        minlength: 2,
        messages: {
          required: "Required input",
          minlength: jQuery.validator.format("Field needs to be more than{0}")
        }
      });
      

      更多信息可以在https://jqueryvalidation.org/rules/找到

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-27
        • 1970-01-01
        • 2010-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        相关资源
        最近更新 更多