开发者

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-开发者_如何学JAVAF0-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" e.g.:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜