Kanwal Hanjra
Kanwal Hanjra

Reputation: 201

TextField uppercase and lowercase validation

I am working on textfields validations and getting confused how to validate textfield must contain at least 1 character from all of the following categories: English uppercase characters (A - Z). English lowercase characters (a - z).

Upvotes: 2

Views: 1750

Answers (4)

Amit gupta
Amit gupta

Reputation: 553

func isValidPassword(testStr:String?) -> Bool {
    guard testStr != nil else { return false }
 
    // at least one uppercase, 
    // at least one lowercase
    // 8 characters total
    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "(?=.*[A-Z])(?=.*[a-z]).{8,}")
    return passwordTest.evaluate(with: testStr)
}

Upvotes: 0

Taimoor Suleman
Taimoor Suleman

Reputation: 1616

Credit : TextField uppercase and lowercase validation

Here is the regext for the condition :- Minimum 8 characters, 1 uppercase and 1 number.

^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,}

extension String {
func isValidPassword() -> Bool {
    let regularExpression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
    let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)

    return passwordValidation.evaluate(with: self)
    }
}

//Example 1

var password = "@Abcdef011" //string from UITextField (Password)
password.isValidPassword() // -> true

//Example 2

var password = "wer011" //string from UITextField 
password.isValidPassword() // -> false

Upvotes: 1

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119310

Simple extension accepts any CharacterSet to check:

extension String {
    func hasCharacter(in characterSet: CharacterSet) -> Bool {
        return rangeOfCharacter(from: characterSet) != nil
    }
}

usage:

"aBc".hasCharacter(in: .lowercaseLetters)
"aBc".hasCharacter(in: .uppercaseLetters)

Upvotes: 0

pbodsk
pbodsk

Reputation: 6876

Have a look at CharacterSets (described here)

You can create various Character sets (lowercase letters for instance) and test whether a string has content that matches said character set.

So, you could create a function which returns a boolean. The function checks your string against two CharacterSets and only if both can be found in the string, does the function return true.

Something like this

func validate(string: String) -> Bool {
    let lowercase = CharacterSet.lowercaseLetters
    let uppercase = CharacterSet.uppercaseLetters

    let lowercaseRange = string.rangeOfCharacter(from: lowercase)
    let uppercaseRange = string.rangeOfCharacter(from: uppercase)

    return lowercaseRange != nil && uppercaseRange != nil
}

validate(string: "Hello") //returns true
validate(string: "hello") //returns false
validate(string: "HELLO") //returns false

Have a look at this article from NSHipster to learn more.

Upvotes: 2

Related Questions