Search code examples
cocoaxcodeuser-inputsanitize

Filtering/Sanitizing User Input. Best Approach


To clarify, I want to check for valid characters. For first name, last name I want to check for [A-Za-z]. For Email I want to check for chars valid for email.

What algorithm would I use to CHECK user input? Specifically, I'd like to CHECK the user's first name, last name and email address for valid characters before I add to database.

Obviously, something like this isn't sufficient:

    if ( [firstName.text isEqualToString:@""] || [lastName.text isEqualToString:@""] || [emailAddress.text isEqualToString:@""]) { ... }

Solution

  • Revised for your edit:

    What you probably want to look at is NSCharacterSet. It lets you define explicit sets of characters, which you can then use to test strings for presence of those characters. A trivial example:

    NSCharacterSet* nonAlphaNumericSet = [[NSCharacterSet alphanumericCharacterSet] invertedSet];
    if ([someString rangeOfCharacterFromSet:nonAlphaNumericSet].location != NSNotFound)
    {
        NSLog(@"It's not alphanumeric!");
    }