LoginSignup
1
2

More than 1 year has passed since last update.

[Swift]簡単な入力バリデーションを実装してみる

Last updated at Posted at 2022-05-12

はじめに

アプリの初回登録時などにバリデーションを走らせたいことが多いと思うので
簡単なサンプルを載せておきます。
※個人的な使い回しも兼ねて

コード

Validation.swift

import Foundation


enum ValidationResult {
    case valid
    case nameIsEmpty(section: String)
    case ageIsEmpty(section: String)
    case birthdayIsEmpty(section: String)
    
    var isValid: Bool {
        switch self {
        case .valid:
            return true
        case .nameIsEmpty:
            return false
        case .ageIsEmpty:
            return false
        case .birthdayIsEmpty:
            return false
        }
    }   
    var errorMessage: String {
        switch self {
        case .valid:
            return ""
        case .nameIsEmpty(let section):
            return "\(section)の入力がありません"
        case .ageIsEmpty(let section):
            return "\(section)の入力がありません"
        case .birthdayIsEmpty(let section):
            return "\(section)の入力がありません"
        }
    }
}

final class Validator {
    
    static let shared: Validator = .init()
    private init() {}
    
    func validationCheck(name: String?, age: Int?, birthday: String?) -> ValidationResult {
        
        guard let name = name, !name.isEmpty else {
            return .nameIsEmpty(section: "名前")
        }
        
        guard let age = age else {
            return .ageIsEmpty(section: "年齢(数字)")
        }
        
        guard let birthday = birthday, !birthday.isEmpty else {
            return .birthdayIsEmpty(section: "誕生日")
        }
        
        return .valid
    }
    
}


使い方

例えば登録ボタンを押して、その時に走らせたいのであれば下記をボタンタップのコード内に記載します

ViewController.swift
let result = Validator.shared.validationCheck(name: "受け取る値", age: "受け取る値", birthday: "受け取る値")

switch result.isValid {
case true:
    // 問題なかった場合の処理(保存するとか)
case false:
    // 問題があった場合の処理(エラー返す)
}

終わりに

今回は簡単なバリデーションを実装してみました。

パスワード時も応用すればできると思うので、また更新します。

間違ってる箇所があればご教授いただけると幸いです。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2