How to validate field using Combine in SwiftUI

DevTechie
DevTechie
Published in
7 min readAug 25, 2022

--

Photo by Jerin J on Unsplash

In scenarios where we ask users to fill out information, we also want to make sure that the data entered by the user is correct. Which is where field validation comes into picture.

Fields can vary based on the requested information so does the logic for validation.

If we take simple sign-up page with username, password and confirm password fields as an example. All three fields would require different validation rules.

In this article, we will use Apple’s Combine framework to add validations. Here is what our end product will look like:

Let’s get started. We will start with the brain of this project, meaning combine logic for validation.

Start by creating a new “Swift” file and name it “DevTechieSignUpVM”

We will import combine framework with the line below:

import Combine

This file will contain ViewModel for sign up page and it will be a final class as we are not planning to subclass. We also want to conform to the ObservableObject protocol, which will help us publish events to our UI.

--

--