我想创建一个用户名输入,我想限制用户的输入onkeypress。可以输入的字符数限制是20 + 1是固定的前缀。如何限制连续使用相同的字符?
我想实现的是:
- 要限制用户输入并只接受A-Z,0-9,破折号( - )和下划线(_)。 [解决]
- 禁止用户使用破折号( - )或下划线(_)启动他们的用户名。 [解决]
- 禁止用户使用破折号( - ),如果他们使用了下划线(_)和相反。 [已解决]
- 允许用户最多使用3个破折号( - )或3个下划线(_)。 [解决破折号]
- 要禁止用户使用连续的符号,像这样(user___或用户 - P等)[!求助]
似乎我无法弄清楚是怎么将下划线(_)限制为3 max,并且如何停止连续破折号( - )和下划线(_)。
任何帮助和正确的解释将不胜感激!
我的HTML:
<form name = "RegForm" method="post" action="index.html" class="login">
<input type="text" maxlength = "21" name="userID" id="userID"/>
</form>
我的javascript:
var userID_textfield = document.forms.RegForm.userID;
userID_textfield.onkeypress = function(e) {
// Invalid character list
var prohibited = "[email protected]#$%^&*()+=;:`~\|'?/.><, \"";
// List of characters that can't be first
var posRestricted = "-_";
// List of characters that can't be used more than once
var numRestricted = "-_";
// Get the actual character string value
var key = String.fromCharCode(e.which);
/* Goal:
Validate: Accept only a-z, 0-9, - and _ */
if (prohibited.indexOf(key) >= 0) {
console.log('Invalid key pressed');
return false;
}
else {
/* Goals:
1. Validate: -, _ and 0-9 can't be first
2. Validate: - and _ can't be last if the userID is 21 characters long */
if ((posRestricted.indexOf(key) >= 0 && this.value === "@") || (numRestricted.indexOf(key) >= 0 && this.value.length === 20)) {
console.log("Username can't start with a number, a dash (-) or an underscore (_)");
return false;
}
/* Goals:
1. Validate: - and _ can't be used more than once each
2. Validate: if - exists _ can't be used and the opposite' */
else if (numRestricted.indexOf(key) >= 0) {
var numResValue = [0, 0];
for (var a = 0; a < numRestricted.length; a++) {
for (var b = 0; b < this.value.length; b++) {
if (this.value.charAt(b) === numRestricted[a]) {
numResValue[a] += 1;
}
}
}
for (var c = 0; c <= numResValue.length; c++) {
if (numResValue[c] < 3) {
if (this.value.indexOf(numRestricted.replace(key, "")) === -1) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
else {
return true;
}
}
};
您可以在行动here查看代码。
为5 。仅适用于 - 和_?还是所有角色? – Arg0n
它适用于“ - ”和“_”。其余的字符,除了A-Z,0-9, - 和_都被禁用。 –
你可以用正则表达式来完成,或者你可以通过将最后一个字符的跟踪保存在像s.charAt(s.length-1)这样的字符串中,并在你选择的eventListener中禁止新字符。 – Redu