SwiftUIFormValidator
SwiftUIFormValidator copied to clipboard
How to get localized validation messages?
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?
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)
}
}
}
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")