问题描述
要将输入字段限制为仅字母数字,请在我的网站上使用以下内容:
To restrict an input field to alphanumeric only, I use the following on my site:
<input
type="text"
name="url_code"
pattern="[a-zA-Z0-9_-]{4,10}"
class="widefat-main"
title="4 to 10 alphanumerical characters only"
/>
但是对于不支持HTML5的浏览器,获得相同限制的最佳方法是什么?
However for browsers that don't support HTML5, what is the best way to get the same restrictions?
推荐答案
您将需要使用JavaScript来检查输入.在您的< form>
标记中, onsubmit
属性需要调用一个函数,该函数将返回一个 boolean
值.True表示表单将通过,false表示将不会通过.
You will need to use JavaScript to check the input then. In your <form>
tag, the onsubmit
attribute needs to call a function that will return a boolean
value. True means that the form will go through, false, means that it won't.
使用文档选择器获取 input
元素,然后检查其 value
属性.确保长度正确.然后将其与正则表达式匹配.(在此处了解有关它们的信息:正则表达式)事情还好,返回true.否则返回false,或者在控制台中打印出什么错误,或者将其写入< div>
.如果您希望像HTML5那样弹出窗口,则必须做一些其他事情.
Use a document selector to get the input
element and then check its value
attribute. Make sure it is the right length. Then match it against a regular expression. (Learn about them here: Regular Expressions) If everything thing is fine, return true. Otherwise return false and either print in the console what was wrong or write it to a <div>
. If you want a pop-up like you get with the HTML5 way, you'll have to do some other magic.
请注意 return validate();
,如果您未将其包含在 onsubmit =
中,那么它将无法正常工作,您可以必须具有返回.
Note the return validate();
If you don't include that in your onsubmit=
then it won't work, you must have the return.
<!DOCTYPE html>
<html>
<head>
<title>Validate</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.widefat-main{
}
</style>
<script>
function validate() {
var errorDiv = document.getElementById("errorDiv"),
regex = /^[a-z0-9]+$/,
str = document.getElementById("inputString").value;
if ((str.length > 4) && (str.length < 10) && regex.test(str)) {
errorDiv.innerHTML = "Fine string";
return true;
}
else {
errorDiv.innerHTML = "4 to 10 alphanumerical characters only";
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit="return validate();">
<input
id="inputString"
type="text"
name="url_code"
class="widefat-main"
title="4 to 10 alphanumerical characters only"
/>
<input type="submit" value="Submit"/>
</form>
<div id="errorDiv"></div>
</body>
</html>
这篇关于仅在不使用HTML5的情况下将输入字段限制为字母数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!