You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过jQuery实现无ID表单的客户端验证?

无ID表单的jQuery客户端验证方案

因为表单无法添加ID,我们可以通过属性选择器或类选择器定位元素,实现客户端验证需求。

实现代码

先确保页面已引入jQuery,然后添加以下脚本:

// 监听表单提交事件,通过asp-action属性定位目标表单
$('form[asp-action="Authenticate"]').submit(function(e) {
    // 在当前表单内,通过name属性获取用户名和密码输入框的值,去除首尾空格
    const username = $('input[name="Username"]', this).val().trim();
    const password = $('input[name="password"]', this).val().trim();
    
    // 验证用户名或密码是否为空
    if (!username || !password) {
        // 阻止表单默认提交行为
        e.preventDefault();
        // 弹出提示信息
        alert('please enter username and password');
    }
});

代码说明

  • $('form[asp-action="Authenticate"]'):利用表单的asp-action属性精准定位目标表单,完全避开ID需求
  • $('input[name="Username"]', this):限定在当前表单范围内查找元素,避免页面其他同名输入框干扰
  • trim():过滤输入内容的首尾空格,防止用户仅输入空格绕过验证
  • e.preventDefault():验证不通过时,阻止表单提交到后端

备选方案(类选择器定位)

如果name属性也存在变动风险,可通过类选择器结合位置索引定位:

$('form').submit(function(e) {
    // 获取当前表单内所有带form-control类的输入框
    const formInputs = $(this).find('.form-control');
    // 第一个输入框为用户名,第二个为密码
    const username = formInputs.eq(0).val().trim();
    const password = formInputs.eq(1).val().trim();
    
    if (!username || !password) {
        e.preventDefault();
        alert('please enter username and password');
    }
});

内容的提问来源于stack exchange,提问作者VigneshrajS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:35:34