Swift正则表达式验证邮箱手机号等

邮箱

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

手机号

    func validateMobile() -> Bool {
        let phoneRegex: String = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(17[0,0-9]))\\d{8}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluateWithObject(self)
    }

密码

    func validatePassword() -> Bool {
        let  passWordRegex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$"
        let passWordPredicate = NSPredicate(format: "SELF MATCHES%@", passWordRegex)
        return passWordPredicate.evaluateWithObject(self)
    }

昵称

    func validateNickname() -> Bool {
        let nicknameRegex = "^[\u{4e00}-\u{9fa5}]{4,8}$"
        let passWordPredicate = NSPredicate(format: "SELF MATCHES%@", nicknameRegex)
        return passWordPredicate.evaluateWithObject(self)
    }

车牌号

     func validateCarNum() -> Bool {
        let carString = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
        let carPredicate = NSPredicate(format: "SELF MATCHES %@", carString)
        return carPredicate.evaluateWithObject(self)
    }

用户名

     func validateUserName() -> Bool {
        let userNameRegex = "^[A-Za-z0-9]{6,20}+$"
        let userNamePredicate = NSPredicate(format: "SELF MATCHES %@", userNameRegex)
        let peopleName = userNamePredicate.evaluateWithObject(self)
        return peopleName
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容