仅检测输入文本中的字母(使用javascript时出错)

时间:2012-12-06 19:51:18

标签: javascript jsp

我写的函数检查输入是否是一个字母。如果没有,则显示警告消息,然后删除内容。当我输入一个字母时,它工作正常,但是如果我输入数字,它会显示输入字母的信息,但是当我在框中输入字母时,它仍会弹出信息并要求我输入一封信。为什么?我该如何解决?

<%//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/>

2 个答案:

答案 0 :(得分:2)

您可以将值设置为空格,而不是字母。

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

答案 1 :(得分:0)

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