Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jul 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Validating the character: ?

    Hey guys!
    I have one missing part on my code...

    Here it is:

    Code:
    var srch = "?Test_1234-";
    var valid = /^[A-Za-z0-9_-]{9,25}$/;
    if ( valid.test( srch ) )
    {
    //etc...
    }
    I need to validate srch if it contains only a-zA-Z0-9 _-?...min 9 and max 25 of length
    The only problem I have is with the ? (question sign) character. I don't know how and where to place it in the valid variable...
    Any ideas?
    Thanks a lot in advance!!

  • #2
    Regular Coder
    Join Date
    Mar 2011
    Posts
    148
    Thanks
    0
    Thanked 20 Times in 20 Posts
    Hi
    Add the \ character before special characters in regexp pattern.
    In your code:
    Code:
    var valid = /^[A-Za-z0-9\?_-]{9,25}$/;

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,688
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    And as a minor improvement: \w is shorthand for [A-Za-z0-9_]

    SO you could use
    Code:
    var valid = /^[\w\?\-]{9,25}$/;
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,316
    Thanks
    203
    Thanked 2,565 Times in 2,543 Posts
    For the record, the META characters which must be escaped in a pattern are: ^ $ \ / ( ) | ? + * [ ] { } . (but not , )
    Strictly the hyphen - does not need to be escaped in a pattern unless it is in a character class [] - and not then if it is the last character before the ].

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •