Skip to content

Instantly share code, notes, and snippets.

View Arrlindii's full-sized avatar

Arlind Aliu Arrlindii

  • Munich, Germany
View GitHub Profile
func isEmailValid(_ value: String) -> Bool {
do {
if try NSRegularExpression(pattern: "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$", options: .caseInsensitive).firstMatch(in: value, options: [], range: NSRange(location: 0, length: value.count)) == nil {
return false
}
} catch {
return false
}
return true
}
class Validator {
func isEmailValid(_ value: String) -> Bool {....}
}
func validate() {
if Validator().isEmailValid(email:emailTextField.text) {
validatedEmail = emailTextField.text
}else {
showAlert(for: "Invalid Email")
}
}
struct ValidationError: Error {
var message: String
init(_ message: String) {
self.message = message
}
}
func validatedEmail(_ value: String) throws -> String {
do {
if try NSRegularExpression(pattern: "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$", options: .caseInsensitive).firstMatch(in: value, options: [], range: NSRange(location: 0, length: value.count)) == nil {
throw ValidationError("Invalid e-mail Address")
}
} catch {
throw ValidationError("Invalid e-mail Address")
}
return value
}
protocol ValidatorConvertible {
func validated(_ value: String?) throws -> String
}
enum ValidatorType {
case email
case password
case username
case projectIdentifier
case requiredField(field: String)
func validate() {
let emailValidator = VaildatorFactory.validatorFor(type: .email)
do {
try emailValidator.validate(emailTextField.text)
}catch(let error) {
showAlert(for: (error as! ValidationError).message)
}
let validatedEmail = emailTextField.text!
}
extension UITextField {
func validatedText(validationType: ValidatorType) throws -> String {
let validator = VaildatorFactory.validatorFor(type: validationType)
return try validator.validated(self.text!)
}
}
func validate() {
do {
let email = try emailTextField.validatedText(validationType: ValidatorType.email)
} catch(let error) {
showAlert(for: (error as! ValidationError).message)
}
}
func validate() {
do {
let email = try emailTextField.validatedText(validationType: ValidatorType.email)
let username = try usernameTextField.validatedText(validationType: ValidatorType.username)
let age = try self.ageTextField.validatedText(validationType: ValidatorType.age)
let password = try passwordTextField.validatedText(validationType: ValidatorType.password)
let projectId = try projectIdTextField.validatedText(validationType: ValidatorType.projectIdentifier)
let department = try self.departmentTextField.validatedText(validationType: .requiredField(field: "Department"))
let data = RegisterData(email: email, password: password, username: username, projectID: projectId, department: department, age: Int(age)!)
save(data)