Email validation using NSFormatter

102 views Asked by At

I know this maybe an invalid question.

For email validation, I will go with regex and NSPredicate. But I was asked this, hence trying to get your views on this.

How to use NSFormatter to validate an NSTextField for an email address?

I can do it without NSFormatter using regex. But just curious to know is this possible to do it using NSFormatter?

If yes, how? Any guidance will be helpful.

2

There are 2 answers

1
Wonixer A On

Use this code

  extension String {
// This code is for checking if url is valid, to do email, you need to change the `regEx`
        var validURL: Bool {
            get {
                let regEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
                let predicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [regEx])
                return predicate.evaluate(with: self)
            }
        }
    }
0
Caleb On

But just curious to know is this possible to do it using NSFormatter?

NSFormatter is intended to be subclassed, with each subclass corresponding to a particular kind of data. That's why we have NSDateFormatter, NSNumberFormatter, NSMassFormatter, etc.

As far as I'm aware, the Foundation framework doesn't provide an NSFormatter subclass specifically for email addresses, so you'll need to either find one that someone else has written or write your own. Take a look at NSPersonNameComponentsFormatter for an example of how your EmailFormatter class might work. There's an ancillary NSPersonNameComponents class that contains the various pieces of a full name, and the formatter has methods like -stringFromPersonNameComponents: and -personNameComponentsFromString: to convert between the components object and a string.

You'll probably want to do something similar: create a class or structure that can contain the various parts of an email address, and then write methods that converts an instance of that class to and from a string. To use the formatter to validate an address given as a string, use the formatter to convert the string to your components object, and then check that all the required fields in that object have legitimate values.