简体   繁体   English

Javascript,检查相同字符

[英]Javascript, check for identical characters

I got to make a script for checking an input box (password) for the same characters occuring twice. 我必须编写一个脚本来检查输入框(密码)是否出现两次相同的字符。 This should be used alongside with regex validation (that's already fully working). 这应该与正则表达式验证一起使用(已经可以正常使用)。
To succeed I know that I need to use a (for?) loop somehow, that checks if one character appear twice. 为了成功,我知道我需要某种方式使用(for?)循环,该循环检查一个字符是否出现两次。 Now this is a kind of odd thing to ask for. 现在这是一种奇怪的要求。 I know. 我知道。 But I'm not entirely sure about the conditions for the function. 但是我不确定该功能的条件。 If anyone have any suggestions around how this could be made, that would be great. 如果有人对如何做到这一点有任何建议,那就太好了。 An example: "ABad12" - will pass, whilst "AbAc12" will return false. 例如:“ ABad12”-将通过,而“ AbAc12”将返回false。 Thanks in advance. 提前致谢。

function checkForm(form)


{

 var re = /^\w{6,10}$/;

  if(!re.test(form.pwd1.value)) {
  alert("Error: Password has to be in-between 6-10 characters!");
  form.inputfield.focus();
  return false;
  }


}

Above goes an example of what script I'd like to combine it with (among with more regex validations). 上面是我想将其与哪些脚本结合使用的示例(以及更多的正则表达式验证)。

That's how I would do this: 这就是我要这样做的方式:

var str = "ABad12",
    valid = str.split("").filter(function(e, i, a) {
        return a.indexOf(e) !== i;
    }).length === 0;

if (!valid) {
    // ...
}

But note that array filter() method is not available in old browsers, so check browser compatibility page in advance. 但是请注意,数组filter()方法在旧的浏览器中不可用,因此请提前检查浏览器的兼容性页面

you do not need a for loop. 您不需要for循环。 a simple regex is enough: 一个简单的正则表达式就足够了:

(\w)\1+


var validateRegEx=/(\w)\1+/;
validateRegEx.test("aa") -> return true;
validateRegEx.test("ab") -> return false;

Here's simple (though a bit brute-force) code, pure JavaScript with no regexp: 这是简单的(虽然有点蛮力)代码,没有正则表达式的纯JavaScript:

function check(s) {
  var i;
  for(i = 0; i < s.length - 1; i++) {
    if(s.indexOf(s.substring(i,i+1), i+1) >= 0) {
      return false;
    }
  }
  return true;
}

It simply processes the string from the start and checks for each character whether that character appears later in the string. 它只是从头开始处理字符串,并检查每个字符是否该字符稍后出现在字符串中。

If you integrate this into your code, you could issue a specific message. 如果将此代码集成到代码中,则可以发出特定消息。 Before return false , you could call an error reporting function asking it to show eg 'Error: character “' + s.charAt(i) + '” appears more than once.' return false之前,您可以调用一个错误报告功能,要求它显示例如'Error: character “' + s.charAt(i) + '” appears more than once.'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM