How to validation using Regex TextFields in SwiftUI like a Pro

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 ✅:

if 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❤️.






