#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    6
    Rep Power
    0

    Regular expression problem


    Hi all,

    I am trying to create a regular expression that will allow
    lower/upper letter, numbers, - , _ and ' (apostrophe) and spaces

    This is what I have: /^[a-zA-Z0-9-_]+$/

    when I try to add ' to it I get javascript error. the above doesn't work too It gives me a failed condition even when I only have letters and spaces in the field.

    Thanks
  2. #2
  3. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3887
    a-z, A-Z, 0-9 and underscore are covered by \w. Your current regexp doesn't have a space in it, which explains the fail condition in your last comment. Try:
    Code:
    ^[\w' -]+$
    Depending on how you declare the regexp in JavaScript, you may have to escape the apostrophe (single quote) with a backslash before it.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    6
    Rep Power
    0
    This is my function:

    function validateName(fld,nam){
    var error = "";
    var illegalChars = /^[\w' -]+$/;

    if (fld.value == "") {
    fld.style.background = 'Yellow';
    error = "You didn't enter a "+ nam +".\n";
    } else if (fld.value.length > 50) {
    fld.style.background = 'Yellow';
    error = ""+ nam +" is too long.\n";
    } else if (illegalChars.test(fld.value)) {
    fld.style.background = 'Yellow';
    error = "Only letters, Numbers, - _ are allowed in "+ nam +"\n";
    } else {
    fld.style.background = 'White';
    }

    return error;
    }

    These are the values I have in the field:

    firstname: Drew
    lastname: Baskets

    And it shows the error msg after testing the regexpression. I am not sure why it fails!!
  6. #4
  7. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3887
    That regular expression will match only valid strings. It looks like you're giving the error message whenever it does match, so it's backwards.

IMN logo majestic logo threadwatch logo seochat tools logo