2012-12-06 23 views
0

我寫的函數檢查輸入是否是字母。如果沒有,則顯示警告消息,然後擦除內容。當我輸入一個字母時,它可以正常工作,但如果輸入數字,它會顯示輸入字母的信息,但是當我在信箱中輸入字母時,它仍會彈出消息並要求我輸入一個字母。爲什麼?我該如何解決它?僅檢測輸入文本中的字母(使用javascript的錯誤)

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

回答

0

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

+0

現在的作品,那是什麼意思? – keivn

+0

它忽略值的開始和結尾處的空格。 – redolent

+1

'^'匹配字符串的開頭,'\ s'表示一個空白字符,'*'表示零或多個,所以'\ s *'是零個或多個空格字符。 '[A-Za-z]'當然是A-Z或a-z範圍內的字母,'+'是一個或多個,'$'是字符串的結尾。 https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions –

2

將該值設置爲空格,該空格不是字母。

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

+0

但我需要在this.value之後將值設置爲空格 – keivn

+1

@keivn,我認爲沒有理由需要這樣做。 –

+0

,因爲我需要防止用戶在提交之前輸入數字 – keivn

相關問題