jquery 通过JavaScript自定义客户端验证

qlvxas9a  于 2023-01-12  发布在  jQuery
关注(0)|答案(2)|浏览(114)

我正在开发一个MVC 5的项目。有一些表单输入字段,我需要使用jquery/javascript进行自定义客户端验证。预期的行为是,例如,当有人试图在电话输入中键入字母或特殊字符时,在该字段下面应该显示验证错误,或者至少应该触发包含该错误的警报框。我已经在我的scripts文件夹中添加了自定义验证文件。我可以看到我在页面的控制台上写的一些基本日志。我在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 of the field使其工作。

sdnqo3pr

sdnqo3pr1#

你需要把上面的代码附加到一个事件中,比如输入或者提交。现在它只运行一次,当页面加载的时候
比如

$(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');
  });
});
gg0vcinb

gg0vcinb2#

我建议在视图上使用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/

相关问题