通过 ASP.NET 核心 Jquery 验证来验证表单的 Javascript 函数

Javascript function to validate form by ASP.NET Core Jquery validation

提问人: 提问时间:11/23/2022 最后编辑:Manoj Joshi 更新时间:11/24/2022 访问量:782

问:

我正在尝试通过 ASP.NET Core JQuery 验证(项目中提供的验证)来验证 ASP.NET Core 表单而不刷新页面。当我正常发布表单时,验证工作正常。但是我想使用 AJAX 发布表单,所以我运行 preventDefault() js 函数以通过 ajax 手动提交。但似乎这个函数正在破坏验证(无需刷新即可工作的那个)。这意味着即使表单有错误,它也会提交!

这是我的cshtml文件:

@page
@model Baunity.Web.Pages.Dash.EditProfileModel

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

<p id="verificationAlert" style="display: none !important;" class="alert alert-success">text</p>


@section Scripts {
    @{
        await Html.RenderPartialAsync ("_ValidationScriptsPartial");
    }
    }

    <form method="post">
        <input asp-for="Email" />
        <label asp-for="Email"></label>
        <span asp-validation-for="Email"></span>

        <br />

        <input asp-for="Username" />
        <label asp-for="Username"></label>
        <span asp-validation-for="Username"></span>

        <br />

        <input asp-for="Password" />
        <label asp-for="Password"></label>
        <span asp-validation-for="Password"></span>

        <br />

        <input asp-for="ConfirmPassword" />
        <label asp-for="ConfirmPassword"></label>
        <span asp-validation-for="ConfirmPassword"></span>

        <br />

        <input asp-for="FirstName" />
        <label asp-for="FirstName"></label>
        <span asp-validation-for="FirstName"></span>

        <br />

        <input asp-for="LastName" />
        <label asp-for="LastName"></label>
        <span asp-validation-for="LastName"></span>

        <br />

        <div id="verificationForm" style="display: none !important;">
            <input asp-for="VerificationCode" />
            <label asp-for="VerificationCode"></label>
        <span asp-validation-for="VerificationCode"></span>

        </div>

        <div asp-validation-summary="ModelOnly"></div>

        <br />

        FIX DOING OTHER STUFF LIKE SETTING VALUES AT BACKEND

        <input type="submit" id="submit" onclick="SubmitForm(this.parentElement, event)" />
    </form>

    <p>@ViewData["DONE"]</p>

网站.js

let isVerificationEmailSent = false;

function SubmitForm(frm, caller) {
    debugger;

    if (!isVerificationEmailSent) {
        caller.preventDefault();
    }
    else {
        return;
    }

    var fdata = new FormData();

    var emailData = $('#Email').val();
    fdata.append("Email", emailData);

    var usernameData = $('#Username').val();
    fdata.append("Username", usernameData);

    var passwordData = $('#Password').val();
    fdata.append("Password", passwordData);

    var confirmPasswordData = $('#ConfirmPassword').val();
    fdata.append("ConfirmPassword", confirmPasswordData);

    var firstNameData = $('#FirstName').val();
    fdata.append("FirstName", firstNameData);

    var lastNameData = $('#LastName').val();
    fdata.append("LastName", lastNameData);

    let isSuccess = true;

    $.ajax(
        {
            type: frm.method,
            url: frm.action,
            headers:
            {
                "XSRF-TOKEN": $("input[name='__RequestVerificationToken']").val()
            },
            data: fdata,
            processData: false,
            contentType: false,
            statusCode: {
                912: function (responseObject, textStatus, jqXHR) {
                    $("#verificationForm").show();
                    $("#verificationAlert").show();
                    isVerificationEmailSent = true;
                },
            },
            success: function (data) {
                alert(data);
                isSuccess = true;
            },
            error: function (data) {
                if (!isSuccess) {
                    alert('ERROR' + data);
                }
            }
        })
}

我尝试在jquery中使用&函数,但它给了我错误。我想要一种类似于这两种方法的方法。valid()validate()

javascript jquery asp.net asp.net-core unobtrusive-validation

评论


答:

0赞 Xinran Shen 11/24/2022 #1

如果不想使用提交表单,为什么要设置?您可以像这样设置按钮:submit buttontype="submit"

<button type="button" onclick="SubmitForm(this.parentElement)">submit</button>

在这种情况下,您不需要再使用。event.preventDefault()

为表单设置一个 ID:

<form method="post" Id="Form">...</form>

然后在你的js代码中:

let isVerificationEmailSent = false;

function SubmitForm(frm) {

    $('#Form').validate();

  if ($('#Form').valid() === true) {
     var fdata = new FormData();

     var emailData = $('#Email').val();
    fdata.append("Email", emailData);

    var usernameData = $('#Username').val();
    fdata.append("Username", usernameData);

    var passwordData = $('#Password').val();
    fdata.append("Password", passwordData);

    var confirmPasswordData = $('#ConfirmPassword').val();
    fdata.append("ConfirmPassword", confirmPasswordData);

    var firstNameData = $('#FirstName').val();
    fdata.append("FirstName", firstNameData);

    var lastNameData = $('#LastName').val();
    fdata.append("LastName", lastNameData);

    let isSuccess = true;

    $.ajax(
        {
            type: frm.method,
            url: frm.action,
            headers:
            {
                "XSRF-TOKEN": $("input[name='__RequestVerificationToken']").val()
            },
            data: fdata,
            processData: false,
            contentType: false,
            statusCode: {
                912: function (responseObject, textStatus, jqXHR) {
                    $("#verificationForm").show();
                    $("#verificationAlert").show();
                    isVerificationEmailSent = true;
                },
            },
            success: function (data) {
                alert(data);
                isSuccess = true;
            },
            error: function (data) {
                if (!isSuccess) {
                    alert('ERROR' + data);
                }
            }
        })
    }
}

评论

0赞 11/24/2022
谢谢。但我的问题实际上不是这个。我想在发送该ajax之前确保表单有效(在前端)。
0赞 Xinran Shen 11/24/2022
嗨,@Matin mohammadi,检查我在 js 中提供的代码,我添加了 '$('#Form').validate();“ 方法,只能发送 ajax,否则会显示错误消息。$('#Form').valid() === true
0赞 11/25/2022
你好,又来了。我以前试过。但它给了我错误:Uncaught TypeError: $(...)。validate 不是 SubmitForm (VM85 site.js:91:16) 的函数 在 HTMLButtonElement.onclick (EditProfile:101:65)
0赞 Xinran Shen 11/25/2022
此错误意味着您的 jquery 验证插件未正确加载。我已经测试了上面的代码,效果很好。