-1

I am new to Swift programming. Trying to build a login page with username and password fields with non empty validation

This is the code for validation using Combine:

private var isUsernameValid: AnyPublisher<Bool, Never> {
        $username
            .debounce(for: 0.2, scheduler: RunLoop.main)
            .removeDuplicates()
            .map {
                if $0.isEmpty {
                self.errorUsername = "Invalid Username"
                return false
            } else {
                self.errorUsername = ""
                return true
            } }
            .eraseToAnyPublisher()
    }
    
    private var isPasswordValid: AnyPublisher<Bool, Never> {
        $password
            .debounce(for: 0.2, scheduler: RunLoop.main)
            .removeDuplicates()
            .map {
                if $0.isEmpty {
                self.errorPassword = "Invalid Password"
                return false
            } else {
                self.errorPassword = ""
                return true
            } }
            .eraseToAnyPublisher()
    }
    
    private var isFormValid: AnyPublisher<Bool, Never> {
        Publishers.CombineLatest(isUsernameValid, isPasswordValid)
            .debounce(for: 0.2, scheduler: RunLoop.main)
            .map { $0 && $1 }
            .eraseToAnyPublisher()
    }

As soon as I enter login page error message is showing. I only want validation error to show after user starts typing into text field. Please help

Rijo Samuel
  • 281
  • 3
  • 10

1 Answers1

1

You can use .dropFirst() to get rid of the initial value (ie the empty field).

$username
  .dropFirst()
  .debounce(for: 0.2, scheduler: RunLoop.main)

.dropFirst can also take an Int argument to drop x number of values before the rest of the publisher chain gets called, which can often be useful.

jnpdx
  • 45,847
  • 6
  • 64
  • 94