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

    Join Date
    Jan 2009
    Posts
    2
    Rep Power
    0

    Regex help required urgently


    I have been trying to create a regex code to validate a string field in a form. below is what is required for the regex code:

    The length of the input is bigger than 0 and less/equal to 14;
    Only letters a to z (lower case), "-" (dash) and " " (space) are allowed,
    The "-" (dash) and " " (space) letters must be entered,
    The "-" or the " " letter must not be either the first or the last letter entered,
    "-" must not be the immediate neighbour or adjacent (before or after) to a " ",
    "-" or " " must not be the immediate neighbour (adjacent) of itself.

    if anyone can help me create the code i would be very grateful.

    cheers 4d4m
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,115
    Rep Power
    9398
    Whee! Help to know the language and regex flavor you're dealing with though. Perl?
    Code:
    /^(?=.{1,14}$)[a-z]+(-[a-z]+ | [a-z]+-)([a-z]+[- ])*[a-z]+$/i
    • ^: Starting at the beginning of the string, this:
    • (?=.{1,14}$): (ensures that there's 1 to 14 characters and then the end of the string*)
    • [a-z]+: checks that there is at least one letter
    • (-[a-z]+ : then a hyphen, letters, and a space
    • | [a-z]+-): or a space, letters, and a hyphen
    • ([a-z]+[- ])*: then some letters and a hyphen or space (repeated any number of times, or not at all)
    • [a-z]+$: and finally at least one more letter before the end of the string

    /i means case-insensitive.

    * Honestly, I'd remove this part and use whatever your language offers to check string length. Like a .length property, strlen function, len() method...

    Tested against
    Code:
    abcdefghijklmn
    abcd fghij-lmn
    a-cd fghij-lmn
    a-cd -ghij-lmn
    a-cd fghij-lm-

    Comments on this post

    • ManiacDan agrees : Wow, this was helpful! Who are you and how much to get requinix back?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2009
    Posts
    2
    Rep Power
    0
    I am going to be using the regex within Javascript to validate a name field on an online form.

    cheers

    4d4m

    Comments on this post

    • ManiacDan disagrees : (0) You'll need to validate it on the server-side as well.

IMN logo majestic logo threadwatch logo seochat tools logo