0

I'm trying to regex on the client as well as the server with this validation of a Base64 encoded 256-bit number without the = padding.

^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]$

This is my code which isn't working as expected as any value seems to return true:

$.fn.validateKey = function() {
    var re = /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]$/
    var re = new RegExp($(this).val());
    return re;
};

How can I validate Base 64 encoded 256-bit signing keys without padding with javascript?

1 Answers1

3

You're returning a RegExp object. You want to return its evaluation with an input string instead.

$.fn.validateKey = function() {
    var re = /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]$/;
    return re.test($(this).val());
};

Jan in the comments pointed out something interesting, in which the / doesn't need to be escaped in the regex (at least in my browser).

I believe it's due to being part of a character class.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • Thank you so much alex! What do you mean by that last comment? I'm using this answer to validate a properly formatted Base64 encoding of a 256-bit number. http://stackoverflow.com/a/21151612/1382306 Is there some other pitfall that I'm missing? Thank you very much in advance! –  Jan 18 '14 at 20:35
  • @Gracchus I jumped the gun. If it's a subset of encoded data (a number only), you should be right. It's also possible I'm on holidays and forgot a lot of programming. – alex Jan 18 '14 at 20:37
  • I hear you! Thanks again! –  Jan 18 '14 at 20:45
  • does the slash inside the character group not need escaping? How so? – John Dvorak Jan 18 '14 at 20:46
  • Usually, the delimeter's parse the string which is sent to the regex engine. I would imagine it is seeing this `/^[A-Za-z0-9+/` as the regex, which should throw an error of unmatched `[`. But, this is JS so I am not sure. –  Jan 18 '14 at 21:10