[英]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:您可以将return
语句替换为:
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:或者,您可以像上面一样保留您的验证 function,然后执行以下操作:
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()
:如果您想在文档本身中显示错误消息,那么您可以执行类似的操作,并将上面的alert()
替换为error()
:
function error(message) {
document.getElementById("error").innerHTML = message;
}
This assumes that you have an element in your HTML with id="error"
eg:这假设您的 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");
}
Working Example: http://jsfiddle.net/Q9qVU/工作示例: http://jsfiddle.net/Q9qVU/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.