最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Determine if string has any characters that aren't in a list of characters and if so, which characters don&

programmeradmin2浏览0评论

I'm working on a simple password validator and wondering if its possible in Regex or... anything besides individually checking for each character.

Basically if the user types in something like "aaaaaaaaa1aaaaa", I want to let the user know that the character "1" is not allowed (This is a super simple example).

I'm trying to avoid something like

if(value.indexOf('@') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}

Maybe something like:

if(/[^A-Za-z0-9]/.exec(value) {}

Any help?

I'm working on a simple password validator and wondering if its possible in Regex or... anything besides individually checking for each character.

Basically if the user types in something like "aaaaaaaaa1aaaaa", I want to let the user know that the character "1" is not allowed (This is a super simple example).

I'm trying to avoid something like

if(value.indexOf('@') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}

Maybe something like:

if(/[^A-Za-z0-9]/.exec(value) {}

Any help?

Share Improve this question asked Jan 15, 2015 at 22:33 CharlieCharlie 1,7465 gold badges24 silver badges43 bronze badges 5
  • Seems to be a reasonable approach in the case when only letters and numbers are allowed. – PM 77-1 Commented Jan 15, 2015 at 22:36
  • Yes, it is usually possible with regex, but you didn't specify what are the password requirements, is it just all letters? – elclanrs Commented Jan 15, 2015 at 22:36
  • 3 I'll just point out that any password system that artificially, and arbitrarily, limits the characters I can use for my password is not a system I trust to be secure. – David Thomas Commented Jan 15, 2015 at 22:38
  • if(/[^A-Za-z0-9]/.exec(value) {} this approach (despite missing a bracket ) ). Is the most simplest way of doing. Except update to: if(/[^A-Za-z0-9]+$/.exec(value)) {} – Mouser Commented Jan 15, 2015 at 22:40
  • Arg. I can only pick one answer! That sucks. In case anyone comes across this one in the future, there's quite a few awesome answers here. – Charlie Commented Jan 15, 2015 at 23:40
Add a comment  | 

4 Answers 4

Reset to default 10

If you just want to check if the string is valid, you can use RegExp.test() - this is more efficient that exec() as it will return true when it finds the first occurrence:

var value = "abc$de%f";

// checks if value contains any invalid character
if(/[^A-Za-z0-9]/.test(value)) {
   alert('invalid');
}

If you want to pick out which characters are invalid you need to use String.match():

var value = "abc$de%f";

var invalidChars = value.match(/[^A-Za-z0-9]/g);

alert('The following characters are invalid: ' + invalidChars.join(''));

Although a simple loop can do the job, here's another approach using a lesser known Array.prototype.some method. From MDN's description of some:

The some() method tests whether some element in the array passes the test implemented by the provided function.

The advantage over looping is that it'll stop going through the array as soon as the test is positive, avoiding breaks.

var invalidChars = ['@', '#', '\\'];

var input = "test#";

function contains(e) {
    return input.indexOf(e) > -1;
}

console.log(invalidChars.some(contains));    // true

I'd suggest:

function isValid (val) {
  // a simple regular expression to express that the string must be, from start (^)
  // to end ($) a sequence of one or more letters, a-z ([a-z]+), of upper-, or lower-,
  // case (i):
  var valid = /^[a-z]+$/i;

  // returning a Boolean (true/false) of whether the passed-string matches the
  // regular expression:
  return valid.test(val);
}

console.log(isValid ('abcdef') ); // true
console.log(isValid ('abc1def') ); // false

Otherwise, to show the characters that are found in the string and not allowed:

function isValid(val) {
  // caching the valid characters ([a-z]), which can be present multiple times in
  // the string (g), and upper or lower case (i):
  var valid = /[a-z]/gi;

  // if replacing the valid characters with zero-length strings reduces the string to
  // a length of zero (the assessment is true), then no invalid characters could
  // be present and we return true; otherwise, if the evaluation is false
  // we replace the valid characters by zero-length strings, then split the string
  // between characters (split('')) to form an array and return that array:
  return val.replace(valid, '').length === 0 ? true : val.replace(valid, '').split('');

}

console.log(isValid('abcdef')); // true
console.log(isValid('abc1de@f')); // ["1", "@"]

References:

  • JavaScript conditional operator (assessment ? ifTrue : ifFalse).
  • JavaScript Regular Expressions.
  • String.prototype.replace().
  • String.prototype.split().
  • RegExp.prototype.test().

If I understand what you are asking you could do the following:

function getInvalidChars() {
    var badChars = {
       '@' : true,
       '/' : true,
       '<' : true,
       '>' : true
    }
    var invalidChars = [];        

    for (var i=0,x = inputString.length; i < x; i++) {
        if (badChars[inputString[i]]) invalidChars.push(inputString[i]);
    }
    return invalidChars;
}
    
var inputString = 'im/b@d:strin>';
    
var badCharactersInString = getInvalidChars(inputString);
    
if (badCharactersInString.length) {
    document.write("bad characters in string: " + badCharactersInString.join(','));
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论