开发者

YA Javascript Regex Question

Trying to do some javascript form val开发者_高级运维idation through JQuery and a Validation plugin.

I'm doing custom validation rule, with an input value that much match this rule...

A-z 0-9 - _ ' & .

Basically, I can't figure out the ' & . parts. Here's what I have now...

/^[A-z0-9_]+(-)+$/i

...I don't know if that's ideal by any means, it works for what it covers.

But, what is the best way to do a regex test for the characters above? Thanks.


If you want to match any of your above stated match criteria, any number of times then the following code should work:

/^[a-zA-Z0-9&_.\-']+$/

I've included some below test examples noting in the comments when the pattern should be valid or invalid:

<script type="text/javascript">
    //A-z 0-9 - _ ' & .
    //valid
    var test_string = "This'Is'-Val1d&_.";
    if (test_string.match(/^[a-zA-Z0-9&_.\-']+$/)){
        alert("first test matched");
    }else{
        alert("first test did not match");
    }

    //invalid - whitespace not allowed
    test_string = "This IsNot- Va'l1d & _ .";
    if (test_string.match(/^[a-zA-Z0-9&_.\-']+$/)){
        alert("second test matched");
    }else{
        alert("second test did not match");
    }

    //invalid - ! is not allowed
    test_string = "'ThisIsNotValid!'";
    if (test_string.match(/^[a-zA-Z0-9&_.\-']+$/)){
        alert("third test matched");
    }else{
        alert("third test did not match");
    }

</script>


Is this what you want?

var regex = /^[a-z0-9_\-.'&]/i;


Not totally sure I understand what you're trying to match, but it looks like you want any combination of letters, numbers, or the symbols -_'&.. If that's the case, use this:

/^[-\w.'&]+$/

Note that the + could be removed or replaced with * depending on how many characters you want to match.


Edit - A little explanation of what this means:

  • [- - When - is used at the beginning of a character class, it counts as a literal -. If it's used inside [] brackets other than right at the beginning or end of the class, it indicates a range such as A-Z or 0-9.
  • \w - Matches any letter, any number, or a _ symbol. This is usually equivalent to [a-zA-Z0-9_].
  • .'& - Inside a character class, these have no special meaning other than the literal characters.
  • + - Means "at least once". You could replace this with * if you want to allow an empty string, remove it if you only want one character, or use a quantifier like {8}.

More info at regular-expressions.info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜