-1

I am working on a username regex where the only characters that are accepted are a-z, A-Z, 0-9, and _. The current max length of the username is 18 characters with a minimum of one. My current regex is below.

let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$"

I am having the following issue. Special characters added anywhere but the end of the string allow the regex to pass. For example

jon! FAIL

!jon PASS

j!on PASS

The method I am using to test the regex is below along with the calling method. Any input would be greatly appreciated.

Regex Testing Method

func regexTestString(string: String, withPattern regexPattern: String) -> Bool
{
        // This method is used for all of the methods below.  
        do
        {
            // Create regex and regex range.
            let regex = try NSRegularExpression(pattern: regexPattern, options: .CaseInsensitive)
            let range = NSMakeRange(0, string.characters.count)

            // Test for the number of regex matches.
            let numberOfMatches = regex.numberOfMatchesInString(string, options: [], range: range)

            // Testing Code.
            print(numberOfMatches)

            // Return true if the number of matches is greater than 1 and return false if the number of mathces is 0.
            return (numberOfMatches == 0) ? false : true
        }
        catch
        {
            // Testing Code
            print("There is an error in the SignUpViewController regexTestString() method \(error)")

            // If there is an error return false.
            return false
        }
    }

Calling Method

func usernameTextFieldDidEndEditing(sender: AnyObject)
    {
        let usernameText = self.usernameField.text!.lowercaseString

        let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$"
        let regexWhitespacePattern = "\\s"
        let regexSpecialCharacterPattern = ".*[^A-Za-z0-9].*"

        if regexTestString(usernameText, withPattern: regexCorrectPattern)
        {
            // The regex has passed hide the regexNotificationView

        }
        else if regexTestString(usernameText, withPattern: regexWhitespacePattern)
        {
            // The username contains whitespace characters.  Alert the user.
        }
        else if regexTestString(usernameText, withPattern: regexSpecialCharacterPattern)
        {
            // The username contains special characters.  Alert the user.
        }
        else if usernameText == ""
        {
            // The usernameField is empty.  Make sure the sign up button is disabled.
        }
        else
        {
            // For some reason the Regex is false.  Disable the sign up button.
        }
    }
jonthornham
  • 2,881
  • 4
  • 19
  • 35

1 Answers1

1

You want the entire string to contain only the characters you specified, so all you need is to add ^ at the start of the pattern:

^[a-zA-Z0-9_]{1,18}$

Allen Zeng
  • 2,635
  • 2
  • 20
  • 31