我正在尝试创建一个用户名输入,我想限制用户在按键时的输入。可输入的字符限制为 20 + 1 为固定前缀。
我想实现的是:
- 限制用户输入,只接受 A-Z、0-9、破折号 (-) 和下划线 (_)。 [已解决]
- 禁止用户的用户名以破折号 (-) 或下划线 (_) 开头。 [已解决]
- 如果用户使用了下划线 (_) 或反义词,则禁止用户使用破折号 (-)。 [已解决]
- 允许用户最多使用 3 个破折号 (-) 或 3 个下划线 (_)。 [破折号解决]
- 禁止用户使用像这样的连续符号(user___ 或 user--p 等)[需要帮助!]
我似乎无法弄清楚的是如何将下划线 (_) 限制为最多 3 个以及如何停止连续的破折号 (-) 和下划线 (_)。
任何帮助和适当的解释将不胜感激!
我的 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 = "!@#$%^&*()+=;:`~\|'?/.><, \"";
// List of characters that can't be first
var posRestricted = "-_0123456789";
// 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;
}
}
};
可以查看action here中的代码。
最佳答案
你可以添加这个:(我更新了 fiddle :https://jsfiddle.net/ck7f9t6x/5/)
var lastKey = this.value.charAt(this.value.length-1);
alert("lastKey = " + lastKey);
if(lastKey == key){
return false;
}
else{
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;
}
}
...
}
关于javascript - 如何限制同一个字符连续使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37136863/