TextField输入验证模式

时间:2016-11-04 15:07:25

标签: swift validation input textfield

在ViewController中,我有三个文本字段(邮件,密码,重复密码)。在将数据发送到服务器之前,我做了一点验证(检查文本是否存在,邮件是否有效等)。

我这样做:

let email = emailTextfield.text
let password = passwordTextfield.text
let repeatPassword = repeatPasswordTextfield.text

        if let e = email {
            if let p = password {
                if let rp = repeatPassword{

                    if(e.isEmpty || p.isEmpty || rp.isEmpty){//cut mail validation...

问题是:这是最好的方法吗?有没有更好的(可能更紧凑)的方式?提前谢谢。

4 个答案:

答案 0 :(得分:0)

从Swift 2.0开始,您不再需要构造an optional binding pyramid of doom,但可以在同一if语句中使用多个绑定(以及布尔条件)。 E.g:

if let email = emailTextfield.text, !email.isEmpty,
   let password = passwordTextfield.text, !password.isEmpty,
   let repeatPassword = repeatPasswordTextfield.text, !repeatPassword.isEmpty  {
    // proceed only for all non-nil and non-empty above ...
}

对于第一次失败的绑定/ false条件满足,这些自然会短路。

答案 1 :(得分:0)

我不确定,但我可以看到两个解决方案:

- 第一个更清楚:

if let e = email, let p = password, let rp = repeatPassword {
    if e.isEmpty || p.isEmpty || rp.isEmpty {
        // do your things
    }
}

- 第二个更紧凑:

if email != nil, password != nil, repeatPassword != nil, (email!.isEmpty || password!.isEmpty || repeatPassword!.isEmpty) {
    // do the things force unwrapping every variable
}

第二个解决方案有效,因为如果电子邮件或密码或repeatPassword为零,则编译器不会继续读取条件,因此不会因为读取而导致读取错误,例如repeatPassword!.isEmpty为nil.isEmpty

为了建立@dfri的答案,我可以想到这个解决方案(未经测试):

if let e = email, let p = password, let rp = repeatPassword, (e.isEmpty, p.isEmpty, rp.isEmpty) {
     // cut mail validation
} 

最后一个,如果有效,显然是最优雅的解决方案,只要@dfri更新他的解决方案以符合您的答案,我就会删除它:)

答案 2 :(得分:0)

if let email = emailTextfield.text where !email.isEmpty,
    let password = passwordTextfield.text where !password.isEmpty,
    let repeatPassword = repeatPasswordTextfield.text where !repeatPassword.isEmpty  {
    // Go for it.
}

答案 3 :(得分:-1)

你可以这样做 if email?.isEmpty || password?.isEmpty || repeatPassword?.isEmpty { //break }

不要担心零值,让它作为选项,一切都会好的。