Search code examples
jqueryregexregular-language

Regular expression for not allowing special char at end and the string length should be in between 3-25


I want to write a regular expression using jQuery to validate input fields which will not allow special char at end and the string length should be in between 3-25.

currently I have an expression which will not allow special char at the end

([0-9a-zA-Z\s])$

for length I tried

([0-9a-zA-Z\s])${3,25} 

but getting error preceding character is not quantifiable.

some valid inputs

abc#123
a%scsd

Invalid Inputs

abc453&
ab
123%

Solution

  • Use a negative lookahead to check if a line contain a special character at the last or not. And also use a positive lookahead to specify that the string length must be from 3 to 25. The below regexes would match the strings only if both conditions are satisfied.

    (?!.*[\W_]$)(?=^.{3,25}$).* 
    

    DEMO

    OR

    (?=.*[A-Za-z0-9]$)(?=^.{3,25}$).*
    

    DEMO