avatarMuhammad naufal adli

Summary

The provided web content is a comprehensive guide on implementing regular expression (RegEx) validation for a Passport Number input field in SwiftUI.

Abstract

The article delves into the utilization of regular expressions for pattern matching in strings within SwiftUI applications, emphasizing the importance of input validation for user experience and data accuracy. It introduces the concept of RegEx and demonstrates how to integrate RegEx validation into a SwiftUI TextField to ensure that a Passport Number conforms to a specific format. The guide provides a step-by-step approach to creating a user interface for a Passport Number input field, implementing validation functions with a sample RegEx pattern, and adding a submission button to trigger the validation process. The article concludes by highlighting the feedback mechanism for users based on the validation results.

Opinions

  • The author, Muhammad Naufal Adli, advocates for the use of RegEx in SwiftUI to enhance the robustness of user input validation.
  • RegEx is presented as an essential tool for developers aiming to enforce stringent input formats, such as Passport Numbers.
  • The article suggests that integrating RegEx validation into SwiftUI applications can significantly improve data accuracy and user experience by providing immediate feedback on input validity.
  • The author's enthusiasm for SwiftUI and RegEx is evident as they encourage readers to stay tuned for more related articles and invite them to show appreciation through clapping.
  • The mention of the article being hand-crafted and made with love indicates the author's dedication and attention to detail in providing high-quality content to the developer community.

How to validation using Regex TextFields in SwiftUI like a Pro

source: Software Development Notes

Introduction

Regular expressions, commonly known as RegEx, are powerful tools for pattern matching in strings. In SwiftUI, integrating RegEx validation into TextFields can enhance the user experience and ensure data accuracy. In this article, we’ll explore the basics of RegEx, and then dive into implementing RegEx validation for a Passport Number input field in SwiftUI.

Regex, short for Regular Expression, is a sequence of characters that defines a search pattern. It provides a concise and flexible means for matching strings, making it ideal for tasks such as input validation. In the context of SwiftUI, Regex can be used to enforce specific patterns for user input, such as a Passport Number format.

Let’s Create Main View

Let’s consider a Passport Number input field in SwiftUI, represented by the following code snippet:

struct IdentityView: View {
    @State var numberPassport = ""

    var body: some View {
        HStack(spacing: 0) {
            TextField("Number Passport", text: $numberPassport)
                .multilineTextAlignment(.center)
                .font(.custom("Quicksand-Regular", size: 19))
                .foregroundColor(Color("but"))
        }
        .padding(15)
        .overlay(
            RoundedRectangle(cornerRadius: 50)
                .stroke(Color("search"), lineWidth: 2)
        )
        .padding(.horizontal, 35)
        .padding(.vertical, 8)
    }
}

Now, let’s integrate RegEx validation into the code. Add the following functions to validate the Passport Number format:

struct IdentityView: View {
    @State var numberPassport = ""

    var body: some View {
        HStack(spacing: 0) {
            TextField("Number Passport", text: $numberPassport)
                .multilineTextAlignment(.center)
                .font(.custom("Quicksand-Regular", size: 19))
                .foregroundColor(Color("but"))
        }
        .padding(15)
        .overlay(
            RoundedRectangle(cornerRadius: 50)
                .stroke(Color("search"), lineWidth: 2)
        )
        .padding(.horizontal, 35)
        .padding(.vertical, 8)
    }

  // add RegEx validation

 func validateNumberPassport() {
        let isValid = isValidsz(count: numberPassport)
        if isValid {
            // Handle the case where the Passport Number is valid
            print("Passport Number is valid")
        } else {
            // Handle the case where the Passport Number is not valid
            print("Passport Number is not valid")
        }
    }

    func isValidsz(count: String) -> Bool {
        let pattern = "([A-Z]|[1-9])[0-9]{6,12}" // number pattern
        let result = NSPredicate(format: "SELF MATCHES %@", pattern).evaluate(with: count)
        print("Validation result:", result)
        return result
    }

}

The regular expression `([A-Z]|[1–9])[0–9]{6,12}` is a powerful tool used for pattern matching in strings, often referred to as RegEx. Let’s break down its components to understand the specific pattern it aims to match.

The expression begins with `([A-Z]|[1–9])`, where the opening and closing parentheses denote a group of options. This group signifies that the input must commence with either an uppercase letter from A to Z or a digit ranging from 1 to 9. In other words, it establishes the starting conditions for the pattern, ensuring that the initial character adheres to these criteria.

The subsequent part, `[0–9]{6,12}`, further refines the pattern. Here, `[0–9]` signifies any digit from 0 to 9. The quantifier `{6,12}` is applied to this digit pattern, indicating that a sequence of digits, ranging in length from 6 to 12 characters, is expected to follow the initial character specified in the first part of the expression.

Combining these elements, the regular expression as a whole is designed to match strings that begin with either an uppercase letter or a specific set of digits, followed by a sequence of digits of varying length. In practical terms, this pattern could be employed for validating Passport Numbers, ensuring that they conform to a defined structure and length, thereby enhancing data accuracy in a SwiftUI application or any other context where such validation is needed.

Adding a Validation Button:

To trigger the validation, let’s add a “Next” button that calls the validateNumberPassport() function:

Button(action: {
    validateNumberPassport()
}, label: {
    Text("Submit")
        .foregroundColor(Color.white)
        .frame(width: geo.size.width * 0.35, height: geo.size.width * 0.15)
        .background(Color("but"))
        .cornerRadius(30)
        .shadow(color: Color.black.opacity(0.07), radius: 40, x: 0, y: 5)
})

you can see in print is valid or not. the valid one is like this ✅:

valid ✅

if not valid ❌:

not valid ❌

Now, your SwiftUI view includes RegEx validation for the Passport Number input field. Users will receive feedback on whether their input conforms to the specified pattern, ensuring data accuracy in your application.

Thanks for reading! Stay tuned for more SwiftUI articles by Muhammad Naufal Adli. which will be coming soon and dont forget to clap. this artikel make Hand-crafted & Made with❤️.

Programming
Swift
iOS App Development
iOS
iOS Development
Recommended from ReadMedium