2

Need some help from you javascript regexp pro's

I have a function that I want to pass in some a "value" and a list of accepted characters. This function works in php, but the javascript variables don't work the same as in php, so I need some guiadance.

I would like to call this function like this:

isAlphaNumeric(myValue, "_-"); 

This would allow any number, or letter as well as the underscore and the hyphen, but no other characters

This is the function I have, but doesn't quite work right.

function isAlphaNumeric(value, allow)
{
    var result = /^[A-Za-z0-9+allow+]+$/.test(value);
    return result;
}

How can I accomplish what I'm after?

Thanks for the help.

Ronedog
  • 2,313
  • 8
  • 43
  • 85

3 Answers3

4

Use RegExp object constructor

function isAlphaNumeric(value, allow)
{
    var re = new RegExp( '^[A-Za-z0-9'+allow+']+$');
    var result = re.test(value);
    return result;
}

or

function isAlphaNumeric(value, allow)
{
    return new RegExp( '^[A-Za-z0-9'+allow+']+$').test(value);
}
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
1

By creating a RegExp() object.

function isAlphaNumeric(value, allow) {
    var re = new RegExp('^[a-z0-9' + (allow ? allow : '') + ']+$');

    return re.test(value);
}
Orbling
  • 20,413
  • 3
  • 53
  • 64
  • (allow ? allow : '') appears to be redundant – RichardTheKiwi Feb 16 '11 at 02:29
  • 1
    @cyberkiwi: Not so, it stops things like undefined and nulls mucking up the string concatenation. – Orbling Feb 16 '11 at 02:32
  • @cyberwiki: Just because the results come back the same, does not mean it is doing it right, worth looking at what it does to the regexp, check this out: http://jsfiddle.net/ASVvW/2/ – Orbling Feb 16 '11 at 02:58
  • lol .. it does work for the question though, since both "null" and "undefined" are contained in `A-Za-z`. Luck – RichardTheKiwi Feb 16 '11 at 03:04
  • 1
    @cyberwiki: Exactly, luck saved the day for you. However, it is *always* good practice to validate incoming values to functions. – Orbling Feb 16 '11 at 03:18
1

Javascript doesn't handle variables inside strings/regexs directly. You have to create the Regex using the constructor like this:

function isAlphaNumeric(value, allow)
{
    var result = new RegExp("^[A-Za-z0-9" + allow + "]+$").test(value);
    return result;
}

Tested on: http://jsfiddle.net/ZLdtw/

Check this other SO question for more info on this concatenation.

Community
  • 1
  • 1
Mariano Desanze
  • 7,847
  • 7
  • 46
  • 67