我正在尝试创建用户名输入,我想限制用户输入onkeypress。可以输入的字符数限制是20 + 1是固定前缀。
我想要实现的目标是:
我似乎无法弄清楚如何将下划线(_)限制为最大值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;
}
}
};
您可以查看操作中的代码here。
答案 0 :(得分:1)
你可以添加:(我更新了小提琴: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;
}
}
...
}
答案 1 :(得分:0)
你可以为这个接受你的字符串的东西编写一个函数,并返回true或false(有效或无效)
function checkConsecutive(string){
//break it to array
var a = string.split('');
//check for consecutive
for(i=0;i<a.length;i++){
if(a[i] == a[i+1]){
return true;
}else{
return false}
}
}
我知道这不是一个完美的解决方案,但它可以发挥作用。
答案 2 :(得分:0)
请参阅this JSFiddle
HTML
i = 1
for x in box:
print (i,x)
i = 2
for x in box:
print (i,x)
i = 3
for x in box:
print (i,x)
i = 4
for x in box:
print (i,x)
i = 5
for x in box:
print (i,x)
的JavaScript
<input type="text" onkeypress="preventConsecutive(this, event)"/>