【问题标题】:How to restrict the same character from being used consecutively?如何限制连续使用相同的字符?
【发布时间】:2016-05-10 11:11:38
【问题描述】:

我正在尝试创建用户名输入,并且我想限制用户的输入 onkeypress。可输入的字符数限制为 20 + 1 为固定前缀。

我想要实现的是:

  1. 限制用户输入并仅接受 A-Z、0-9、破折号 (-) 和下划线 (_)。 [已解决]
  2. 禁止用户以破折号 (-) 或下划线 (_) 开头。 [已解决]
  3. 如果用户使用了下划线 (_),则禁止用户使用破折号 (-),反之亦然。 [已解决]
  4. 允许用户最多使用 3 个破折号 (-) 或 3 个下划线 (_)。 [破折号已解决]
  5. 禁止用户使用像这样的连续符号(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;
        }
    } 
};

您可以查看运行中的代码here

【问题讨论】:

  • 是 5. 仅用于 - 和 _ 吗?还是所有字符?
  • 它用于“-”和“_”。除 A-Z、0-9、- 和 _ 之外的其余字符均被禁用。
  • 您可以使用正则表达式来做到这一点,也可以通过跟踪字符串中的最后一个字符(如 s.charAt(s.length-1))并在您选择的 eventListener 中禁止新字符来实现。

标签: javascript html validation input


【解决方案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;
              }
            }
    ...

}

【讨论】:

  • 做得很好@Asma。不再有连续的破折号和下划线!现在唯一的问题是下划线限制。虽然我已将它们与破折号一起编码为数量不超过 3,但下划线不符合,而破折号符合!你知道是什么原因造成的吗?
  • 其实这里 var numResValue = [0, 0];在这里你有计数器 - 然后是 _ ,所以你必须只测试一个计数器的值(短划线或下划线),而不是在此处更新的 JSFiddle 中的一个循环:jsfiddle.net/ck7f9t6x/6
  • 有效!但是,您能解释一下以下行的作用吗?我以前从未见过这样的事情 :p var indToTest = key === numRestricted[indDash] ? indDash : indUnder;
  • 这一行就像: if (key === numRestricted[indDash] ) { indToTest = indDash; } 其他 { indToTest = indUnder; } “?” = if 和 ":" = else
  • 在需要初始化变量时很有用。
【解决方案2】:

你可以为这个东西写一个函数来接受你的字符串并返回真或假(是否有效)

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}
}
}

我知道这不是一个完美的解决方案,但它可以工作。

【讨论】:

  • 你可以调用这个函数来改变一些东西。
  • 嘿@92sharmasaurabh,我很难理解你的代码。我看到你的代码的方式是检查我输入的下一个字符,所以它实际上是检查一个尚未输入的字符。我看这行不通。如果我错了,请纠正我。
  • 对不起,麻烦老兄...请检查plnkr.co/edit/veuJdKanCcZSRf2BUmHt?p=preview这对我来说很好。
【解决方案3】:

thisJSFiddle

HTML

<input type="text" onkeypress="preventConsecutive(this, event)"/>

JavaScript

function preventConsecutive(el, evt) {
  if(el.value.length > 0) {
    var lastChar = el.value[el.value.length-1];
    if((lastChar === "-" && evt.keyCode === 45) || (lastChar === "_" && evt.keyCode === 95)) {
        evt.preventDefault();
        return;
    }
  }
}

【讨论】:

  • 好吧,你可以替换你代码中的变量名.. el = userID_textfield, evt = e.. 把它放在你自己的onkeypress-功能。
  • 我做到了!这就是我知道它的工作原理:) 我不明白的一件事是这条线是如何工作的:_var lastChar = el.value[el.value.length-1];_ 我不知道你可以得到这个角色像那样。我虽然只能使用 .charAt() 来完成。谢谢你告诉我。
猜你喜欢
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多