web-dev-qa-db-fra.com

Validation du courrier électronique et du téléphone dans Swift

j'utilise le code suivant pour la validation du numéro de téléphone. Mais je reçois l'erreur suivante. Je ne peux pas continuer plus loin. Aidez-nous à le faire avancer.

class PhoneNumberValidation: Validation {
    let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"

    func validate(value: String) -> (Bool, ValidationErrorType) {
        if let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) {
            if phoneTest.evaluateWithObject(value) {
                return (true, .NoError)
            }
            return (false, .PhoneNumber)
        }
        return (false, .PhoneNumber)
    }
}

Erreur: Swift: 15: 28: La valeur liée dans une liaison conditionnelle doit être de type facultatif.

42
Kums

Oui, votre erreur est ci-dessous dans xcode 6.1

enter image description here

Cette erreur est due au fait que IF conditionnel a le type de retour Bool, mais que dans Your si le type de retour est NSPredicate, de sorte que vous obtenez une erreur Swift: La valeur liée dans une liaison conditionnelle doit être de type facultatif vous pouvez le résoudre en tant que au dessous de.

var phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
     if phoneTest.evaluateWithObject(value) {
              return (true, .NoError)
         }
             return (false, .PhoneNumber)
        }

Email-Validations dans Swift.

func isValidEmail(testStr:String) -> Bool {
        print("validate emilId: \(testStr)")
        let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        let result = emailTest.evaluateWithObject(testStr)
        return result
    } 

Utilisation de la validation par courrier électronique:

if isValidEmail("[email protected]"){
        print("Validate EmailID")
    }
    else{
        print("invalide EmailID")
    }

Validation du numéro de téléphone dans Swift

func validate(value: String) -> Bool {
        let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
        let result =  phoneTest.evaluateWithObject(value)
        return result
    }
78
Kirit Modi

Mise à jour pour Swift 2.0

Collez ces lignes n'importe où dans le code (ou dans votre fichier Constant).

extension String {

    //To check text field or String is blank or not
    var isBlank: Bool {
        get {
            let trimmed = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
            return trimmed.isEmpty
        }
    }

    //Validate Email
    var isEmail: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .CaseInsensitive)
            return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
        } catch {
            return false
        }
    }

    //validate PhoneNumber
    var isPhoneNumber: Bool {

        let charcter  = NSCharacterSet(charactersInString: "+0123456789").invertedSet
        var filtered:NSString!
        let inputString:NSArray = self.componentsSeparatedByCharactersInSet(charcter)
        filtered = inputString.componentsJoinedByString("")
        return  self == filtered

    }
}

utilisation de Email Validation:

if(txtEmail.isEmail){
}

Swift 3.0 Solution mise à jour:

// MARK: - Extension de validation -

extension String {

    //To check text field or String is blank or not
    var isBlank: Bool {
        get {
            let trimmed = trimmingCharacters(in: CharacterSet.whitespaces)
            return trimmed.isEmpty
        }
    }

    //Validate Email

    var isEmail: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .caseInsensitive)
            return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
        } catch {
            return false
        }
    }

    var isAlphanumeric: Bool {
        return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
    }

    //validate Password
    var isValidPassword: Bool {
        do {
            let regex = try NSRegularExpression(pattern: "^[a-zA-Z_0-9\\-_,;.:#+*?=!§$%&/()@]+$", options: .caseInsensitive)
            if(regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil){

                if(self.characters.count>=6 && self.characters.count<=20){
                    return true
                }else{
                    return false
                }
            }else{
                return false
            }
        } catch {
            return false
        }
    }
}
31
Sourabh Sharma

Peut-être un meilleur validateur téléphonique dans Swift 2:

extension String {
    var isPhoneNumber: Bool {
        do {
            let detector = try NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue)
            let matches = detector.matchesInString(self, options: [], range: NSMakeRange(0, self.characters.count))
            if let res = matches.first {
                return res.resultType == .PhoneNumber && res.range.location == 0 && res.range.length == self.characters.count
            } else {
                return false
            }
        } catch {
            return false
        }
    }
}
7
EPage_Ed

Le code suivant fonctionne dans xcode 6.3 beta 

func isValidEmail(testStr:String) -> Bool {

   let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
   let range = testStr.rangeOfString(emailRegEx, options:.RegularExpressionSearch)
   let result = range != nil ? true : false
   return result

}

comment l'utiliser: 

Ex. 

if isValidEmail(email.text) == false{
//your code here
}
7
Ronaldoh1

Swift 4+ 

Vous pouvez utiliser regex"^[6-9]\\d{9}$" simplifié

^     #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\\d   #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
{9}   #Repeat the previous "\d" 9 times (9 digits)
$     #Match the end of the string

De référence

Validation Indian Mobile 10 Digit (peut commencer par 6,7,8,9) -

extension String {
    var isValidContact: Bool {
        let phoneNumberRegex = "^[6-9]\\d{9}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
        let isValidPhone = phoneTest.evaluate(with: self)
        return isValidPhone
    }
} 

Utilisation: -

print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false

Pour la validation du courrier électronique, vous pouvez vérifier ceci

6
Jack

Swift 3 Valider Email

class func validateEmail(email: String) -> Bool{

    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"

    return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)

}

Validation du numéro de téléphone

class func validatePhoneNumber(value: String) -> Bool {

    let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
    let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
    let result =  phoneTest.evaluate(with: value)
    return result
}
6
shiju86.v

Swift 3:

private func validate(phoneNumber: String) -> Bool {
    let charcterSet  = NSCharacterSet(charactersIn: "+0123456789").inverted
    let inputString = phoneNumber.components(separatedBy: charcterSet)
    let filtered = inputString.joined(separator: "")
    return  phoneNumber == filtered
}
6
zumzum

Mis à jour pour Swift 3

extension String {
    var isPhoneNumber: Bool {
        do {
            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
            let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.characters.count))
            if let res = matches.first {
                return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.characters.count
            } else {
                return false
            }
        } catch {
            return false
        }
    }
}
5
ajay_nasa

Swift 4.1.

func isValidPhone(phone: String) -> Bool {

      let phoneRegex = "^[0-9]{6,14}$";
      let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
      return valid
   }

func isValidEmail(candidate: String) -> Bool {

       let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
       var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
        if valid {
            valid = !candidate.contains("..")
        }
        return valid
  }
5
GSK

Téléphone regex seulement pour numéro de téléphone Iran

func isValidPhone(phone: String) -> Bool {

        let PHONE_REGEX = "^09[0-9'@s]{9,9}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
        let result =  phoneTest.evaluate(with: phone)
        return result

    }
3

Swift 4+:

func isValidPhone(phone: String) -> Bool {
        let phoneRegex = "^[0-9+]{0,1}+[0-9]{5,16}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with: phone)
    }

func isValidEmail(email: String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: email)
    }

  • +1994423565 - Valide
  • ++ 1994423565 - invalide 
  • 01994423565 - Valide 
  • 001994423565 - Valide 
  • quelque [email protected] - valide 
  • quelque chose @ .com - invalide
2
svmrajesh

Swift 4.2 et Xcode 10.1

//For mobile number validation
func isValidPhone(phone: String) -> Bool {

    let phoneRegex = "^((0091)|(\\+91)|0?)[6789]{1}\\d{9}$";
    let valid = NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phone)
    return valid
}

//For email validation
func isValidEmail(candidate: String) -> Bool {

    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate)
    if valid {
        valid = !candidate.contains("..")
    }
    return valid
}

Utiliser comme ça

//Button Action
@IBAction func onClickRegrBtn(_ sender: UIButton) {
    //Check net connection here
    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg
        SharedClass.sharedInstance.alert(view: self, title: "", message: msg)//Display alert message
    } else {

        let mobileTrimmedString = mobileNoTF.text?.trimmingCharacters(in: .whitespaces) //Trim white spaces

        if mobileTrimmedString != "" {
            if isValidPhone(phone: mobileTrimmedString!) == false {
                SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid mobile number")
            } else {
                UserDefaults.standard.set(mobileTrimmedString, forKey: "mobile") //setObject
                sendMobileNumber()//Call function...
            }

        } else {
            mobileNoTF.text = ""
            //Call alert function
            SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter mobile number")
        }
    }
}
1
iOS

Pour Swift 3.0 et supérieur

var isPhoneNumber: Bool{
let allowedCharacters = CharacterSet(charactersIn: "+0123456789").inverted
let inputString = components(separatedBy: allowedCharacters)
let filtered = inputString.joined(separator: "")
return self == filtered}
1
Hiren Panchal

La réponse de Kirit Modi à propos de la validation de courrier électronique pour Swift 3:

func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$"
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    let result = emailTest.evaluate(with: testStr)
    return result
  }
1
Wilson

Fichier-Nouveau-Fichier.Faites une classe Swift nommée AppExtension.Add ce qui suit.

        extension UIViewController{
            func validateEmailAndGetBoolValue(candidate: String) -> Bool {
                let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
                return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluateWithObject(candidate)
            }
        }

        Use: 
        var emailValidator:Bool?
        self.emailValidator =  self.validateEmailAndGetBoolValue(resetEmail!)
                        print("emailValidator : "+String(self.emailValidator?.boolValue))

        Use a loop to alternate desired results.


    OR
        extension String
        {
        //Validate Email
            var isEmail: Bool {
                do {
                    let regex = try NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
                    return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
                } catch {
                    return false
                }

            }
        }

        Use:
        if(resetEmail!.isEmail)
                        {
                        AppController().requestResetPassword(resetEmail!)
                        self.view.makeToast(message: "Sending OTP")
                        }
                        else
                        {
                            self.view.makeToast(message: "Please enter a valid email")
                        }
0
A.G

Utiliser Swift 3

 func validate(value: String) -> Bool {
    let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
    let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
    let result =  phoneTest.evaluate(with: value)
    return result
}
0
Saneesh

Vous pouvez créer une classe séparée pour la validation comme ci-dessous:

enum AIValidationRule: Int {
case
EmptyCheck,
MinMaxLength,
FixedLength,
EmailCheck,
UpperCase,
LowerCase,
SpecialCharacter,
DigitCheck,
WhiteSpaces,
None

}

let ValidationManager = AIValidationManager.sharedManager


func validateTextField(txtField:AITextField, forRule rule:AIValidationRule, withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {

    switch rule {

    case .EmptyCheck:
        return (txtField.text?.characters.count == 0) ? (false,"Please enter \(txtField.placeholder!.lowercased())",txtField) : nil


    case .MinMaxLength:
        return (txtField.text!.characters.count < minChar || txtField.text!.characters.count > maxChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) to \(maxChar) characters",txtField) : nil

    case .FixedLength:
        return (txtField.text!.characters.count != minChar) ? (false,"\(txtField.placeholder!) should be of \(minChar) characters",txtField) : nil


    case .EmailCheck:
        return (!(txtField.text?.isValidEmail())!) ? (false,"Please enter valid email",txtField) : nil


    case .UpperCase:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.uppercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one uppercase letter",txtField) : nil


    case .LowerCase:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet.lowercaseLetters).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one lowercase letter",txtField) : nil


    case .SpecialCharacter:
        let symbolCharacterSet = NSMutableCharacterSet.symbol()
        symbolCharacterSet.formUnion(with: NSCharacterSet.punctuationCharacters)
        return ((txtField.text! as NSString).rangeOfCharacter(from: symbolCharacterSet as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one special letter",txtField) : nil


    case .DigitCheck:
        return ((txtField.text! as NSString).rangeOfCharacter(from: NSCharacterSet(charactersIn: "0123456789") as CharacterSet).location == NSNotFound) ? (false,"\(txtField.placeholder!) should contain atleast one digit letter",txtField) : nil

    case .WhiteSpaces:
        return (txtField.text!.containsAdjacentSpaces() || txtField.text!.isLastCharcterAWhiteSpace()) ? (false,"\(txtField.placeholder!) seems to be invalid",txtField) : nil

    case .None:
        return nil
    }
}

    func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule]) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {
    return validateTextField(txtField: txtField, forRules: rules, withMinimumChar: 0, andMaximumChar: 0)
}



func validateTextField(txtField:AITextField, forRules rules:[AIValidationRule], withMinimumChar minChar:Int, andMaximumChar maxChar:Int) -> (isValid:Bool, errMessage:String, txtFieldWhichFailedValidation:AITextField)? {

    var strMessage:String = ""
    for eachRule in rules {

        if let result = validateTextField(txtField: txtField, forRule: eachRule, withMinimumChar: minChar, andMaximumChar: maxChar) {
            if(eachRule == AIValidationRule.EmptyCheck){
                return result
            }else{
                strMessage += "\(strMessage.characters.count == 0 ? "" : "\n\n") \(result.errMessage)"
            }
        }
    }
    return strMessage.characters.count > 0 ? (false,strMessage,txtField) : nil
}
0
Dhaval H. Nena

Mis à jour pour Swift:

Utilisé ci-dessous le code pour la validation du courrier électronique, du nom, du mobile et du mot de passe;

// Name validation
func isValidName(_ nameString: String) -> Bool {

    var returnValue = true
    let mobileRegEx =  "[A-Za-z]{2}"  // "^[A-Z0-9a-z.-_]{5}$"

    do {
        let regex = try NSRegularExpression(pattern: mobileRegEx)
        let nsString = nameString as NSString
        let results = regex.matches(in: nameString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

// password validation
func isValidPassword(_ PasswordString: String) -> Bool {

    var returnValue = true
    let mobileRegEx =  "[A-Za-z0-9.-_@#$!%&*]{5,15}$"  // "^[A-Z0-9a-z.-_]{5}$"

    do {
        let regex = try NSRegularExpression(pattern: mobileRegEx)
        let nsString = PasswordString as NSString
        let results = regex.matches(in: PasswordString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

// email validaton
func isValidEmailAddress(_ emailAddressString: String) -> Bool {

    var returnValue = true
    let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"

    do {
        let regex = try NSRegularExpression(pattern: emailRegEx)
        let nsString = emailAddressString as NSString
        let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

// mobile no. validation
func isValidPhoneNumber(_ phoneNumberString: String) -> Bool {

    var returnValue = true
    //        let mobileRegEx = "^[789][0-9]{9,11}$"
    let mobileRegEx = "^[0-9]{10}$"

    do {
        let regex = try NSRegularExpression(pattern: mobileRegEx)
        let nsString = phoneNumberString as NSString
        let results = regex.matches(in: phoneNumberString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

//Comment utiliser?

let isFullNameValid = isValidName("ray")

if isFullNameValid{
    print("Valid name...")
}else{
    print("Invalid name...")
}
0
Kiran jadhav