SwiftUIFormValidator icon indicating copy to clipboard operation
SwiftUIFormValidator copied to clipboard

How to get localized validation messages?

Open jonsaw opened this issue 2 years ago • 1 comments

I'm trying to setup a multilingual app with Localizable.strings. So far, the UI elements in SwiftUI all translate as expected. How do we get the validation messages to translate accordingly?

jonsaw avatar Jun 27 '22 07:06 jonsaw

Got it to work (with extra steps).

extension LocalizedStringKey {
    var stringKey: String {
        let description = "\(self)"
        
        let components = description.components(separatedBy: "key: \"")
            .map { $0.components(separatedBy: "\",") }
        
        return components[1][0]
    }
    
    func stringValue(locale: Locale = .current) -> String {
        return .localizedString(for: self.stringKey, locale: locale)
    }
}

struct LoginView: View {
    @Environment(\.locale) var locale: Locale

    func trValidationMessage(_ message: String) -> some View {
        let localeMessage = LocalizedStringKey(message).stringValue(locale: locale)
        return Text(localeMessage).foregroundColor(Color.red).font(.caption)
    }

    var body: some View {
        TextField("Email", text: $viewModel.email)
            .validation(viewModel.emailValidation) { message in
                trValidationMessage(message)
            }
    }
}

jonsaw avatar Jun 28 '22 05:06 jonsaw

With iOS 16, managed to get it to work simply by using String(localized:)

let emailLabel = String(localized: "Email")
let errorMessage = String(localized: "Valid \(emailLabel) required")

jonsaw avatar Feb 18 '23 04:02 jonsaw