Search code examples
javascriptregexkeyfilter

Regular Expression: Letters, numbers, spaces, hyphens, periods, and underscores only and must begin with a letter


After a few tutorials I thought I had this, but nope ---

I am trying to only match a string of letters, numbers, spaces, hyphens, periods, and underscores only and must begin with a letter in a jquery function

This is what I came up with after the tutorials but it only accepts letters:

/^[a-z][a-z0-9_ .-]*?/i

Please help!

++EDITED++

This is the code where I am trying to use this:

$('input[name=albumName]').keyfilter(/^[a-z][a-z0-9_ .-]*?/i);

The name that a user is entering will also be used in a URL so I want to limit their entry. I would want this to be allowed ( Texas AandM - 2012 ) but this not to be allowed ( 2012 - Texas A&M )


Solution

  • Your regex looks ok to me. Perhaps there is a problem with the surrounding code rather than the regex? This is a Python example:

    s_re = re.compile('^[a-z][a-z0-9_.-]*',re.I) # case insensitive match
    
    In [12]: if s_re.match('A'): print 'match'
    match
    
    In [14]: if s_re.match('A.-'): print 'match'
    match
    
    In [15]: if s_re.match('1.-'): print 'match'
    
    In [16]: if s_re.match('1_.-'): print 'match'
    
    In [17]: if s_re.match('A_.-'): print 'match'
    match
    

    If you want to make sure you want at least one character after the first letter, you can replace the * with a +, or {2,} with at least 2 more characters, or {2,5} with between 2 and 5 characters.