VUE这个验证的代码应该怎样优化一下?

三段都有同样的 这一小段代码 请问应该怎样优化一下重复的代码呢 还有我想问一下表单验证你们都是自己写验证规则吗 还是用插件呢?我这样写是不是很不好

setTimeout(() => {
   ins.close()
}, 800)
return false
if (this.username == '' || this.pw == '' || this.pw2 == '') {
        let ins = this.$toast('用户名或密码不能为空')
        setTimeout(() => {
          ins.close()
        }, 800)
        return false
      } else if (!regPw.test(this.pw) || !regPw.test(this.pw2)) {
        let ins = this.$toast('密码不合法')
        setTimeout(() => {
          ins.close()
        }, 800)
        return false
      } else if (this.pw !== this.pw2) {
        let ins = this.$toast('密码不一致')
        setTimeout(() => {
          ins.close()
        }, 800)
        return false
      }
    }
阅读 2.1k
3 个回答

简单封装一下就好了

function showToast(txt) {
    let ins = this.$toast(txt)
    setTimeout(() => {
        ins.close()
    }, 800)
}

function isEmpty(arr) {
    return arr.some(v => v === '')
}

function isEqual(a, b) {
    return a === b
}

function isPasswordValid(pwd) {
    return regPw.test(pwd)
}

function checkValid() {
    const {username, pw, pw2} = this
    
    if (isEmpty([username, pw, pw2])) {
        showToast('用户名或密码不能为空')
        return false
    }
    if (!isEqual(pw, pw2)) {
        showToast('密码不一致')
        return false
    }
    if (!isPasswordValid(pw)) {
        showToast('密码不合法')
        return false
    }
    return true
}
if (this.username == '' || this.pw == '' || this.pw2 == '') {
        let ins = this.$toast('用户名或密码不能为空')
       
      } else if (!regPw.test(this.pw) || !regPw.test(this.pw2)) {
        let ins = this.$toast('密码不合法')
       
      } else if (this.pw !== this.pw2) {
        let ins = this.$toast('密码不一致')
      }
      
      setTimeout(() => {
          ins.close()
       }, 800)
        return false
    }else {
    // ajax
    }

这样 ?

可以参考elementui的表单验证

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题