Razor Pages 中基于客户端验证的条件表单提交指南

花韻仙語
发布: 2025-09-07 19:40:02
原创
522人浏览过

razor pages 中基于客户端验证的条件表单提交指南

本教程详细阐述了如何在 ASP.NET Core Razor Pages 应用中实现基于客户端 JavaScript 验证的条件表单提交。通过修改 HTML 按钮类型、统一 JavaScript 验证函数的返回值,并利用 jQuery 的 submit() 方法,确保表单仅在所有前端验证规则均通过时才向服务器发送数据,从而提升用户体验和数据完整性。

理解 Razor Pages 中的表单提交机制

在 ASP.NET Core Razor Pages 中,当一个 <button type="submit"> 元素被点击时,浏览器会默认尝试提交其所属的 <form>。如果表单上绑定了 onsubmit 事件处理器,该处理器会在提交前执行。同样,如果按钮上绑定了 onclick 事件,它也会在表单提交流程开始前触发。

原始代码中,提交按钮的定义为 <button onclick="validate()" type="submit" id="submitButton">Sign Up</button>。这里的关键在于 type="submit"。即使 onclick="validate()" 函数被调用,如果 validate() 函数本身没有明确阻止默认行为(例如通过 event.preventDefault() 或返回 false),表单仍然会尝试提交。原始的 validate() 函数仅进行控制台日志输出,并未阻止默认提交,导致即使存在验证错误,表单依然会被发送到服务器。

此外,原始 JavaScript 中部分验证函数(如 checkpass1() 和 checkpass2())的返回值逻辑与其他函数(如 fname())不一致。例如,fname() 在验证失败时返回 true,而在成功时返回 false;而 checkpass1() 在验证失败时返回 false,在成功时返回 true。这种不一致性会使主 validate() 函数的逻辑判断变得复杂且容易出错。

核心解决方案:阻止默认行为并手动控制提交

要实现严格的条件提交,我们需要采取以下策略:

  1. 阻止按钮的默认提交行为:将提交按钮的 type 从 submit 改为 button。这样,点击按钮时将只触发 onclick 事件,而不会自动提交表单。
  2. 统一验证函数返回值:确保所有客户端验证函数都遵循相同的约定,例如:验证失败时返回 true(表示存在错误),验证成功时返回 false(表示无错误)
  3. 在主验证函数中集中判断并提交:在 validate() 函数中,执行所有个体验证,并根据它们的返回值判断表单的整体有效性。只有当所有验证都通过时,才通过 JavaScript 代码手动提交表单。

实施步骤

步骤 1: 调整 HTML 结构

首先,我们需要修改 <form> 标签和提交 <button> 标签。

  1. 为 <form> 元素添加 id: 这使得我们可以在 JavaScript 中通过 ID 轻松引用表单。
  2. 修改 <button> 的 type 属性: 将 type="submit" 改为 type="button"。

修改后的 HTML 代码片段:

<form id="signUpForm" class="mb-3" method="post">
    <!-- ... 其他表单元素 ... -->
    <div class="col-12 d-grid">
        <button onclick="validate()" class="btn btn-primary rounded-pill" type="button" id="submitButton">Sign Up</button>
    </div>
</form>
登录后复制

注意:这里我们将表单 ID 命名为 signUpForm,以避免与 JavaScript 中的 count 变量混淆。

步骤 2: 统一 JavaScript 验证逻辑

为了使 validate() 函数的逻辑清晰和可靠,我们需要确保所有独立的验证函数都遵循相同的返回值约定:当验证失败(存在错误)时返回 true,当验证成功(无错误)时返回 false

表单大师AI
表单大师AI

一款基于自然语言处理技术的智能在线表单创建工具,可以帮助用户快速、高效地生成各类专业表单。

表单大师AI 74
查看详情 表单大师AI

根据这个约定,我们需要修正 checkpass1() 和 checkpass2() 函数。

修正后的 checkpass1() 函数:

const checkpass1 = () => {
    const a = document.getElementById("signUpPassword").value;
    const new1 = document.getElementById("i6");
    const new2 = new1.getElementsByTagName("span");
    const specialChars = /[`!@#$%^&*()_+-=[]{};':"\|,.<>/?~]/;

    if (a.length < 8) {
        new2[0].innerHTML = "Password length must be at least 8 characters";
        new2[0].style.color = "red";
        return true; // 验证失败,返回 true
    } else if (a.length > 12) {
        new2[0].innerHTML = "Password length must not exceed 12 characters";
        new2[0].style.color = "red";
        return true; // 验证失败,返回 true
    } else if (!specialChars.test(a)) {
        new2[0].innerHTML = "Password must contain at least 1 special character";
        new2[0].style.color = "red";
        return true; // 验证失败,返回 true
    } else {
        new2[0].innerHTML = "";
        return false; // 验证成功,返回 false
    }
}
登录后复制

修正后的 checkpass2() 函数:

const checkpass2 = () => {
    const a = document.getElementById("signUpConfirmPassword").value;
    const b = document.getElementById("signUpPassword").value;
    const new1 = document.getElementById("i7");
    const new2 = new1.getElementsByTagName("span");

    if (a !== b) { // 使用 !== 进行严格比较
        new2[0].innerHTML = "Password does not match";
        new2[0].style.color = "red";
        return true; // 验证失败,返回 true
    } else {
        new2[0].innerHTML = "";
        return false; // 验证成功,返回 false
    }
}
登录后复制

其他如 fname(), lname(), checkcountry(), checkMobile(), checkEmail() 等函数已经符合“失败返回 true,成功返回 false”的约定,无需修改。

3. 优化主验证函数 validate()

现在,我们可以修改 validate() 函数来收集所有验证结果,并根据结果决定是否提交表单。我们将使用一个布尔标志来跟踪是否存在任何验证错误。

const validate = () => {
    let hasError = false; // 标志,用于跟踪是否存在任何验证错误

    // 运行所有验证函数。如果任何一个函数返回 true(表示有错误),则将 hasError 设置为 true。
    // 这里使用短路逻辑,但为了确保所有错误信息都显示,最好逐一调用。
    if (fname()) hasError = true;
    if (lname()) hasError = true;
    if (checkcountry()) hasError = true;
    if (checkMobile()) hasError = true;
    if (checkEmail()) hasError = true;
    if (checkpass1()) hasError = true; // 调用修正后的函数
    if (checkpass2()) hasError = true; // 调用修正后的函数

    if (hasError) {
        console.log("Error: Form not submitted due to validation failures.");
        // 不执行提交操作,表单停留在当前页面,用户可以看到错误信息
    } else {
        console.log("Validation successful. Submitting form.");
        // 所有验证通过,使用 jQuery 提交表单
        // 确保页面已引入 jQuery 库,例如 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        $("#signUpForm").submit();
    }
};
登录后复制

完整的 <script> 代码块示例:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入 jQuery -->
<script>
    // ... (fname, lname, checkcountry, checkMobile, checkEmail 等函数保持不变) ...

    const checkpass1 = () => {
        const a = document.getElementById("signUpPassword").value;
        const new1 = document.getElementById("i6");
        const new2 = new1.getElementsByTagName("span");
        const specialChars = /[`!@#$%^&*()_+-=[]{};':"\|,.<>/?~]/;

        if (a.length < 8) {
            new2[0].innerHTML = "Password length must be at least 8 characters";
            new2[0].style.color = "red";
            return true; // Error
        } else if (a.length > 12) {
            new2[0].innerHTML = "Password length must not exceed 12 characters";
            new2[0].style.color = "red";
            return true; // Error
        } else if (!specialChars.test(a)) {
            new2[0].innerHTML = "Password must contain at least 1 special character";
            new2[0].style.color = "red";
            return true; // Error
        } else {
            new2[0].innerHTML = "";
            return false; // Valid
        }
    }

    const checkpass2 = () => {
        const a = document.getElementById("signUpConfirmPassword").value;
        const b = document.getElementById("signUpPassword").value;
        const new1 = document.getElementById("i7");
        const new2 = new1.getElementsByTagName("span");

        if (a !== b) {
            new2[0].innerHTML = "Password does not match";
            new2[0].style.color = "red";
            return true; // Error
        } else {
            new2[0].innerHTML = "";
            return false; // Valid
        }
    }

    const validate = () => {
        let hasError = false;

        // 执行所有验证,如果任何一个返回 true (表示有错误),则设置 hasError 为 true
        if (fname()) hasError = true;
        if (lname()) hasError = true;
        if (checkcountry()) hasError = true;
        if (checkMobile()) hasError = true;
        if (checkEmail()) hasError = true;
        if (checkpass1()) hasError = true;
        if (checkpass2()) hasError = true;

        if (hasError) {
            console.log("Error: Form not submitted due to validation failures.");
            // 此时表单不会提交,错误信息会显示在页面上
        } else {
            console.log("Validation successful. Submitting form.");
            $("#signUpForm").submit(); // 使用 jQuery 提交表
登录后复制

以上就是Razor Pages 中基于客户端验证的条件表单提交指南的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号