簡體   English   中英

讓 javascript 從這個正則表達式測試中提醒用戶

[英]Getting javascript to alert the user from this regex test

我對用戶輸入進行了以下正則表達式測試:

function validate_form() {

return /^[a-fA-F0-9]+$/.test(document.form.input.value);

}

如果用戶輸入不符合標准,那么我將如何在此代碼中發出警報以通知他們?

您可以將return語句替換為:

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

或者,您可以像上面一樣保留您的驗證 function,然后執行以下操作:

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>
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;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM