boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

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


avatar
作者 2025年9月7日 9

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

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

Munch

ai营销分析工具,长视频中提取出最具吸引力的短片

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

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

根据这个约定,我们需要修正 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 中基于客户端验证的条件javascript word java jquery html js 前端 处理器 浏览器 ai 表单提交 red JavaScript jquery html count Event 事件



评论(已关闭)

评论已关闭