TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Phone regex giving out of bounds error

Forums > Swift

Hi all,

I have a function written with Combine to validate a phone number:

        @Published var phone : String = ""
        @Published var isPhoneValid : Bool = false
        func validatePhone() {
            $phone.map { phone in
                let regex = try! NSRegularExpression(pattern: "([+]?1+[-]?)?+([(]?+([0-9]{3})?+[)]?)?+[-]?+[0-9]{3}+[-]?+[0-9]{4}")
                return regex.firstMatch(in: self.phone, options: [], range: NSRange(location: 0, length: phone.utf16.count)) != nil
            }
            .assign(to: &$isPhoneValid)
        }

The phone number is modified via a TextField in SwiftUI.

However, it is giving me this error:

Thread 1: "*** -[NSRegularExpression enumerateMatchesInString:options:range:usingBlock:]: Range or index out of bounds"

I have the exact same code to validate emails and that works perfectly. Why is this out of range? Thanks!

   

I figured it out, I had to change self.phone to phone, so now the code is

@Published var phone : String = ""
@Published var isPhoneValid : Bool = false

func validatePhone() {
            $phone.map { phone in
                let regex = try! NSRegularExpression(pattern: "([+]?1+[-]?)?+([(]?+([0-9]{3})?+[)]?)?+[-]?+[0-9]{3}+[-]?+[0-9]{4}")
                return regex.firstMatch(in: phone, options: [], range: NSRange(location: 0, length: phone.utf16.count)) != nil
            }
            .assign(to: &$isPhoneValid)
        }

   

Do you have examples of the input you are, uh, inputting when you get the error?

   

The app was initially crashing whenever I inputted a number.

If you check my above post, I solved it.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.