Mughees Musaddiq
Mughees Musaddiq

Reputation: 1060

Validation using Regular Expressions in iOS

I'm implementing validation for username field using Regular Expression(Regex) in iOS. I don't want username to start with the word "guest". I tried below code but it's not working.

[txtUserName addRegx:@"^(guest)" withMsg:@"Username Can't start with the word guest"];

Ideas?

Upvotes: 2

Views: 240

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172528

You can try to use this Regex:

^(?!guest).*$

Explanation:

^ assert position at start of the string

(?!guest) Negative Lookahead - Assert that it is impossible to match the regex below guest matches the characters guest literally (case sensitive)

.* matches any character (except newline)

Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]

$ assert position at end of the string

EDIT:

To make it case insensitive you can try this:

^(?i:(?!guest)).*$

Upvotes: 2

realtimez
realtimez

Reputation: 2555

You have to remove the ( ) like the following:

[txtUserName addRegx:@"^guest" withMsg:@"Username Can't start with the word guest"];

Upvotes: 0

Related Questions