0

我写的函数检查输入是否是字母。如果不是,它会显示一条警报消息,然后删除内容。刚输入一个字母的时候效果很好,但是如果我输入数字,它会显示输入字母的消息,这是可以的,但是当我在框中输入字母时,它仍然会弹出消息并要求我输入一个字母。为什么?我该如何解决?

<%//javascript file %>
<script type="text/javascript" >
function allLetter(value)  
{  
 var letters = /^[A-Za-z]+$/;  
 if(value.match(letters))  
   {
    return true;  
   }  
 else  
   {  
   alert("first, last and middle name contain only letters");  
   return false;  
   }  
} 

function checkform ( form )
{
  // see http://www.thesitewizard.com/archive/validation.shtml
  // for an explanation of this script and how to use it on your
  // own website

  // ** START **
  if ((form.firstName.value == "") || (form.lastName.value == "") ) {
    alert("Please enter both your first and last name.");
    form.firstName.focus();
    form.lastName.focus();
    return false ;
  }
  // ** END **
  return true ;
}
</script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Names and country of residence page</title>
</head>
<body>
<%

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

    // Registering Postgresql JDBC driver with the DriverManager
    Class.forName("org.postgresql.Driver");

    // Open a connection to the database using DriverManager
    conn = DriverManager.getConnection(
        "jdbc:postgresql://localhost:5432/assignment1",
        "postgres","Km81920265");


        // Create the statement
        Statement statement = conn.createStatement();

        // Use the created statement to SELECT
        // the student attributes FROM the Student table.
        rs = statement.executeQuery("SELECT * FROM countries_and_states WHERE is_country='t'");


%>

<%//first delcare input %>
Please enter your first name, last name and middle initial:<p>
<form method="get" action="address.jsp" onsubmit="return checkform(this);">
<%//store input into session %>
Your first name :<input type="text" size="15" name="firstName" onchange="if(!allLetter(this.value)){this.value= ' ';} "/><p/>
Your last name  :<input type="text" size="15" name="lastName" onchange="if(!allLetter(this.value)){this.value= ' ';} "/><p/>
Your middle name:<input type="text" size="15" name="middleName" onchange="if(!allLetter(this.value)){this.value= ' ';} "/><p/>
4

2 回答 2

2

您将值设置为一个空格,而不是一个字母。

还值得注意的是,有些人的名字中有空格。数字也是如此。

于 2012-12-06T19:53:31.537 回答
1

更改字母以匹配/^\s*[A-Za-z]+\s*$/或修剪值周围的空白。

于 2012-12-06T19:55:26.140 回答