2011-07-04 8 views

回答

3

您可以用替換return聲明:

var isValid = /^[a-fA-F0-9]+$/.test(document.form.input.value); 
if (!isValid) alert("Your value was invalid."); 
return isValid; 

或者,你可以讓你的驗證功能上面,並做到:

if (!validate_form()) alert("Your value was invalid."); 

如果你想顯示在文檔中的錯誤信息,那麼你可以做這樣的事情,並更換alert()以上error()

function error(message) { 
    document.getElementById("error").innerHTML = message; 
} 

這是假設你有你的HTML元素具有與id="error"例如:

<div id="error"></div> 
+0

這個答案適用於我,順便說一下,我必須取出變量中的第二個右括號。然而,當我做document.write把錯誤消息放在頁面上而不是彈出窗口的警報時,它會清除除了錯誤消息外的所有內容。有什麼建議麼? – RSM

+0

因爲這個原因,我建議不要使用'document.write'。它會一直清除頁面,除非您在頁面加載時使用它。你最好使用如下形式:'document.getElementById(「error」)。innerHTML =「你的值無效。」;'。我會用更長的示例更新我的答案。 –

0
function validate_form() { 

return (/^[a-fA-F0-9]+$/.test(document.form.input.value)) ? "":alert("There is a problem with your input"); 

} 

工作實例:http://jsfiddle.net/Q9qVU/

+0

我喜歡用戶輸入示例在函數中顯示爲硬編碼。用戶可能是一個真正的黑客。 – katspaugh

+0

它只是爲了測試。因爲他沒有發佈html。 –

1
function validate_form() { 

    var alphanumeric = /^[a-fA-F0-9]+$/.test(document.form.input.value); 
    if(!alphanumeric){ alert("Silly human, you cannot use punctuation here!"); } 
    return alphanumeric; 

} 
+0

@Will_Martin我喜歡這個答案,它的工作原理,但是,當我改變警報寫入,以便它只是在屏幕上顯示消息,沒有彈出框然後它不起作用。有什麼建議麼? – RSM

+0

聽起來好像你正在嘗試使用'document.write()'來輸出消息。這隻適用於初始頁面加載。嘗試使用類似'document.getElementById(「whatever」)的內容。innerHTML =「hi」;' - 儘管如果你使用jQuery,它將會是'$(「#whatever」)。html(「hi」); 。其他框架(原型等)有自己的方法來編寫HTML文檔。檢查你的框架的API文檔。 –