Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

能不能出个form表单验证组件之类的 #3364

Closed
songyx95 opened this issue Jul 10, 2020 · 21 comments
Closed

能不能出个form表单验证组件之类的 #3364

songyx95 opened this issue Jul 10, 2020 · 21 comments

Comments

@songyx95
Copy link

小程序的用的比较麻烦

能不能出个form表单验证组件之类的,这样最好不过了

@ltsxs
Copy link

ltsxs commented Jul 11, 2020

+1
希望可以将h5版的form表单校验移植过来

@zhaocchen
Copy link

+1

7 similar comments
@601460003
Copy link

+1

@LYY-castle
Copy link

+1

@xx668888
Copy link

+1

@dxlani
Copy link

dxlani commented Dec 2, 2020

+1

@studylss
Copy link

studylss commented Dec 7, 2020

+1

@a51427051
Copy link

+1

@www295686243
Copy link

+1

@ruyar2020
Copy link

希望出form组件,不然好难写啊

@ghost
Copy link

ghost commented May 20, 2021

+1

1 similar comment
@Albertlws
Copy link

+1

@SSRChen
Copy link

SSRChen commented Jul 22, 2021

2021年了……还是没有

@dxlani
Copy link

dxlani commented Jul 22, 2021

我这里有一个,简单易用,与el,antd2.x的校验类似 有兴趣的私密我吧

@dustq
Copy link

dustq commented Jul 28, 2021

大家都怎么处理form表单提交的

@liangxiaoxin
Copy link

+1

@liangxiaoxin
Copy link

这是我的表单校验代码 @dustq 我使用的是toast提示的方式

const validRules = {
  isPhone: function (value, callback) {
    return (/^1[3|4|5|7|8|9][0-9]\d{4,8}$/.test(value) && value.length === 11)
  },
}
data: {
	rules: {
      name: [
        {
          require: true,
          tips: '请输入姓名'
        }
      ],
      phoneNumber : [
        {
          require: true,
          tips: '请输入手机号'
        },
        {
          validator: validRules.isPhone,
          tips: '手机号输入有误'
        }
      ],
    }
},
save () {
let {rules} = this.data
    let isValid = true
    Object.keys(rules).forEach((key, index) => {
      rules[key].forEach((rule, ruleIndex) => {
        if ((rule.require && !this.data[key]) || (this.data[key] && rule.validator && !rule.validator(this.data[key]))) {
          wx.showToast({
            title: rule.tips,
            icon: 'none',
            mask: true,
          })
          isValid = false
          throw Error(`${key} is Error ${rule.tips}`)
        }
      })
    })
    if (!isValid) {
    	console.log('校验不通过')
      return
    }else {
    	console.log('校验通过')
    }
}

@zhoucumt
Copy link

强烈希望出个form组件,没有form组件还是毕竟震惊

@Joahyan
Copy link

Joahyan commented Sep 18, 2021

https://juejin.cn/post/6995804951754571813 我通常处理表单校验的方式,欢迎点赞

@kong-xb
Copy link

kong-xb commented Aug 17, 2023

2023了,还没有form表单验证组件之类的,双向绑定啊

@forget1
Copy link

forget1 commented Aug 25, 2023

之前封装的表单验证Behavior

import { isString } from '../utils/util'
import Validator from '../libs/validator/index'
import { _ } from '../libs/index'

/**
 * 为组件添加表单能力
 * 生成getForm、validateForm方法
 * 
 * @example
 * 
 * //---- 如何在js里声明校验规则 ----//
 * 
 * import validationBehavior from 'path/to/behaviors/validation'
 * 
 * Component({
 *   behaviors: [
 *     validationBehavior
 *   ],
 *   form: {
 *     fields: ['phone', 'captcha'],
 *     validation: {
 *       phone: {
 *         // 添加校验规则时,参数为字符串表示使用个性化提示信息
 *         required: '请输入手机号',
 *         // 添加校验规则时,参数为true表示使用默认提示信息
 *         tel: true
 *       }
 *     }
 *   },
 *   
 *   submit(event) {
 *      const form = this.getForm()
 *      const [ valid, error ] = this.validate(form)
 * 
 *      if (!valid) {
 *        // 表单验证失败
 *        return
 *      }
 * 
 *      // 继续表单提交
 *   }
 * })
 * 
 */
module.exports = Behavior({
  properties: {
  },
  definitionFilter(defFields) {
    const formDef = defFields.form

    // 处理表单项
    const root = formDef.root
    const fields = defFields.form.fields

    defFields.methods.getForm = function() {
      const fields = defFields.form.fields || this.fields
      const formData = root ? _.get(this.data, root) : this.data
      return fields.reduce((form, field) => {
        form[field] = formData[field]
        return form
      }, {})
    }

    // 处理表单验证
    const validation = defFields.form.validation

    const __validator = validatorFactory(validation)

    function validatorFactory(validation) {
      if (!validation) {
        return null
      }

      const rules = {}
      const messages = {}

      Object.keys(validation).forEach(name => {
        const rule = validation[name]

        rules[name] = Object.keys(rule).reduce((rule, ruleName) => {
          rule[ruleName] = true
          return rule
        }, {})

        messages[name] = Object.keys(rule).reduce((message, ruleName) => {
          if (isString(rule[ruleName])) {
            message[ruleName] = rule[ruleName]
          } else {
  
          }
          return message
        }, {})
      })

      return new Validator(rules, messages)
    }

    defFields.methods.setValidator = function(validation) {
      this.validator = validatorFactory(validation)
    }

    defFields.methods.setFields = function(fields) {
      this.fields = fields
    }

    defFields.methods.getValidator = function() {
      return __validator || this.validator
    }

    defFields.methods.validate = function(form) {
      const validator = this.getValidator()
      const valid = validator.checkForm(form)
      const errors = validator.errorList

      if (!valid) {
        const errorData = errors.reduce((errors, error) => {
          errors[error.param] = error.msg
          return errors
        }, {})

        this.setData({
          errors: errorData
        })
      } else {
        this.setData({
          errors: {}
        })
      }

      return [valid, errors]
    }
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests