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

登录表单JavaScript校验报错:Uncaught TypeError: Cannot read properties of undefined (reading 'uname') 求助排查

Fixing the "Cannot read properties of undefined (reading 'uname')" Error in Your Login Form

Hey there! Let's break down why you're hitting that error and get your validation working as expected.

Root Cause of the Error

The Uncaught TypeError happens because your JavaScript is trying to access document.forms["myform"], but your HTML form only has class="myform"—document.forms uses the form's name attribute to find elements, not the class attribute. This means document.forms["myform"] returns undefined, and trying to read .uname from an undefined value throws the error you're seeing.

Quick Fixes to Get Your Validation Working

Fix 1: Add a name Attribute to Your Form

The simplest fix is to add a name attribute matching what your JS expects to the form tag. Update your HTML form like this:

<form name="myform" class="myform" onsubmit="return vfun()">

Now document.forms["myform"] will correctly locate your form, and the rest of your validation logic will run as intended.

Fix 2: Use getElementById for More Robust Form Selection

If you prefer not to rely on the name attribute, you can use an id instead. Here's how:

  1. Update your HTML form to include an id:
<form id="myform" class="myform" onsubmit="return vfun()">
  1. Modify your JavaScript function to fetch the form by its id:
function vfun(){
  const form = document.getElementById("myform");
  const uname = form["uname"].value;
  const pword = form["pword"].value;

  if (!uname) {
    document.getElementById("errorBox").textContent = "enter the user name";
    return false;
  }
  if (!pword) {
    document.getElementById("errorBox").textContent = "enter the password";
    return false;
  }
  alert("Login successfully");
  return true;
}

(Note: I swapped innerHTML for textContent here—it's safer for plain text content like error messages.)

Bonus: Improve Error Message Experience

Right now, if both fields are empty, only the username error shows up. You could adjust the logic to show both errors if needed:

function vfun(){
  const form = document.getElementById("myform");
  const uname = form["uname"].value;
  const pword = form["pword"].value;
  const errorBox = document.getElementById("errorBox");
  let errors = [];

  if (!uname) errors.push("enter the user name");
  if (!pword) errors.push("enter the password");

  if (errors.length > 0) {
    errorBox.textContent = errors.join(", ");
    return false;
  }

  alert("Login successfully");
  return true;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:47:29