article

Friday, February 11, 2022

SwiftUI Password Strength Checker

SwiftUI Password Strength Checker

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev15ios
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var email : String = ""
    @State var password : String = ""
    @State var passwordStrength : Int = 0
    
    func checkStrength(_ password: String) -> Int {
        let passwordLength = password.count
        var containsSymbol = false
        var containsUppercase = false

        for character in password {
            if "ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(character) {
                containsUppercase = true
            }
            
            if "!£$%&/()=?^;:_รง°§*,.-_".contains(character) {
                containsSymbol = true
            }
        }
        
        if passwordLength > 8 && containsSymbol && containsUppercase {
            return 1
        } else {
            return 0
        }
    }
    
    var body: some View {
        VStack {
            Spacer()
            
            Group {
                TextField("Email", text: $email)
                    .keyboardType(.emailAddress)
                    .autocapitalization(.none)
                TextField("Password", text: $password)
            }
            .padding(16)
            .background(Color.white)
            
            HStack {
                if checkStrength(password) == 0  {
                    Text("Weak").foregroundColor(Color.red)
                        .font(.system(size: 30.0)).padding()
                } else {
                    Text("Strong").foregroundColor(Color.green)
                        .font(.system(size: 30.0)).padding()
                }
            }
            
            Button {

            } label: {
                HStack {
                    Spacer()
                    Text("Log In")
                        .foregroundColor(.white)
                        .padding(.vertical, 10)
                        .font(.system(size: 14, weight: .semibold))
                    Spacer()
                }.background(Color.blue)
                
            }
            
            Spacer()
            
        }.padding()
        .background(SwiftUI.Color.gray.edgesIgnoringSafeArea(.all))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post