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

如何用JavaScript验证表单?姓名字段正则验证需求咨询

Full Name Form Validation in JavaScript (Adjusted to Your Requirements)

Got it, let's tweak your code to meet all the validation rules for the full name field. Here's the breakdown and corrected code:

Issues with Your Original Code

  • The regex /^[a-zA-Z]+$/ only allows letters, so it rejects valid spaces between words and hyphens.
  • There's no check for the minimum (3) and maximum (35) character length.
  • It doesn't prevent leading/trailing spaces or hyphens (which aren't allowed per your rules).

Corrected Validation Function

function test(myForm) {
  // Get the input value and trim any accidental leading/trailing whitespace
  const fullName = myForm.full_name.value.trim();
  const minLength = 3;
  const maxLength = 35;

  // Regex: Allows letters, spaces between words, hyphens between words; no leading/trailing non-letters
  const nameRegex = /^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$/;

  // Check length first
  if (fullName.length < minLength || fullName.length > maxLength) {
    alert(`Name must be between ${minLength} and ${maxLength} characters long`);
    myForm.full_name.focus();
    return false;
  }

  // Check valid characters and structure
  if (!nameRegex.test(fullName)) {
    alert("Name can only contain letters, spaces between words, and hyphens (-). No leading/trailing spaces or hyphens allowed.");
    myForm.full_name.focus();
    return false;
  }

  // All checks passed
  return true;
}

Key Explanations

  1. Trimming the Input: trim() removes any leading/trailing spaces, which helps catch accidental whitespace and ensures we validate the actual name content.
  2. Length Check: Explicitly verifies the name is between 3-35 characters long, with clear user feedback if it's too short/long.
  3. Regex Breakdown:
    • ^[a-zA-Z]+: Starts with one or more uppercase/lowercase letters.
    • (?:[\s-][a-zA-Z]+)*: A non-capturing group that matches a space (\s) or hyphen (-) followed by one or more letters. The * means this can repeat zero or more times (allowing multiple words separated by space/hyphen).
    • $: Ensures the string ends with a letter (no trailing spaces or hyphens).

Example Valid/Invalid Names

  • Valid: "John Doe", "Mary-Anne Smith", "Robert", "Jean-Luc Picard"
  • Invalid: "Jo" (too short), "A name way longer than thirty-five characters definitely" (too long), "John- " (trailing hyphen), "123Jane" (numbers included), "John_Doe" (underscore instead of hyphen)

HTML Input Note

Make sure your input tag is complete (looks like it was cut off in your snippet). Here's a proper example:

<tr>
  <td><b>Full Name: </b></td>
  <td><input type="text" name="full_name" placeholder="Enter your full name" required></td>
</tr>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:10:06