Create a password requirements view with SwiftUI

Samuel Hepditch
2 min readMar 25, 2021

--

A SwiftUI view with a TextField for entering a password and Text elements describing each password requirement. The password requirement Text elements are changing colour, from red to green, based on user input. For example, if the user types in a special character then the associated Text element will change from red to green.

Improving the user experience of your iOS application is of the utmost importance. Fortunately, SwiftUI provides the tools to make high-quality user interfaces. In this blog post, we will create a ‘password requirements view’ that changes dynamically to provide visual feedback to the user when they are typing in their password.

First, let’s create a variable with the @State property wrapper, call it demoPassword, and bind this variable to a TextField. Using the @State property wrapper will trigger the view to refresh when a user has altered the value stored in demoPassword. It is best practice to make @State variables private to avoid an unintentional mutation.

Now, let’s create a few password requirements to enforce. We will record whether the user has met a requirement by storing the associated boolean value in an array. Note, this array is a computed property because we want to dynamically change the interface according to the user’s input. We can check to see if a password meets a requirement by creating a function to detect if specific characters are present in a String. Swift 5 makes this super easy with its clean API for regular expressions.

For our last step display the password requirements to the user via Text elements and determine the foreground colour depending on the value stored in the corresponding element of passwordRequirements.

That’s all folks! For more iOS tutorials consider following this account in the meantime, happy coding.

--

--

Samuel Hepditch

Front End iOS Engineer at Pronti AI Inc. | Studying Computer Science at the University of Waterloo