简体   繁体   中英

Getting javascript to alert the user from this regex test

I have the following regex test on a users input:

function validate_form() {

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

}

I the users input failed to meet the criteria, then how would i get an alert put in this code to inform them?

You could replace the return statement with:

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

Alternatively, you could keep your validation function as above, and do:

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

If you want to show the error message in the document itself, then you could do something like, and replace alert() above with error() :

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

This assumes that you have an element in your HTML with id="error" eg:

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

}

Working Example: http://jsfiddle.net/Q9qVU/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM