Answers for "validate phone number in swift"

0

phone number validation in swift

//(I will assume that you already know the basics of SwiftUI and Swift in general, as I will be mainly going throught the function)
//(If you need more understanding of the views, you can comment and I can try to help, or go to the below websites for documentation)
//https://developer.apple.com/documentation/
//https://switontap.com

//(More help on regular expressions can be found in the link below)
//https://koenig-media.raywenderlich.com/downloads/RW-NSRegularExpression-Cheatsheet.pdf
//(This may or may not allow you to have more understanding on the later regular expression below

//Let's take the example swiftui app below into account

struct ContentView: View {
    
    @State var phoneNumber: String = ""
    
    var body: some View {
        VStack {
            TextField("Enter phone number", text: $phoneNumber)
                .disableAutocorrection(true)
            let isValid = isPhoneNumberValid(phoneNumber)
            Text(String(isValid))
        }
    }
  
    func isPhoneNumberValid(_ phoneNumber: String) -> Bool {
        let phoneRegex = "\\+?1?\\s?[2-9][0-9]{2}\\s?[2-9][0-9]{2}\\s?[0-9]{4}"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: phoneNumber)
    }
}

//So, for the function "isPhoneNumberValid", its arguments are phoneNumber, which is a string, and it returns a boolean (true or false)
//The next line declares the constant phoneRegex, to be a regular expression.
//(NOTE THAT REGEX IS SHORT FOR REGULAR EXPRESSION)
// Now, time to decode what "\\+?1?\\s?[2-9][0-9]{2}\\s?[2-9][0-9]{2}\\s?[0-9]{4}" means

//The first part: \\+?1?\\s?, means that there are 0 or 1 occurences of +, 1 and a space.

//The next part: [2-9][0-9]{2}\\s? means that the first characters needs to be a digit from 2 to 9, and then there are two occurences of digits 0-9.
//After those 2 characters, there can be either a space or no space
//This means that 239 and 740 are valid, but anything that starts with 0 or 1 is not valid

//Following that, the next part [2-9][0-9]{2}\\s? is the same thing as the previous part

//Lastly, [0-9]{4} means that there can be 4 numbers from 0-9.
//This means that 3719 or 0610 are valid, but any character (a-z or A-Z) or anything special character (such as : or | is not valid)
//Next, the code basically checks if the phoneNumber follows this regular expression, and thus returns either true or false

//(If you want to know more about NSPredicates, which is too long to explain):
//https://nshipster.com/nspredicate/
Posted by: Guest on August-14-2021

Code answers related to "validate phone number in swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language