当前位置:   article > 正文

react+antd 简单表单验证_antd react函数校验

antd react函数校验
  1. //验证函数
  2. validate(){
  3. let that =this
  4. let data = {
  5. msg: '',
  6. el:null
  7. }
  8. var getEl = {
  9. 0(key) {
  10. return ReactDOM.findDOMNode(that.refs[key])
  11. },
  12. 1(key) {
  13. return ReactDOM.findDOMNode(that.refs[key]).firstElementChild
  14. },
  15. 2(key) {
  16. return ReactDOM.findDOMNode(that.refs[key]).getElementsByTagName('input')[0]
  17. }
  18. }
  19. //验证规则
  20. let msgGroup = [
  21. {
  22. key: 'tenantPhone',
  23. msg: '手机号不合法哦',
  24. validate: function(data, key) {
  25. let val = data[key]
  26. if(!/^1[345678]\d{9}$/.test(val)) {
  27. return true
  28. }
  29. }
  30. },
  31. {
  32. key: 'startTime',
  33. msg: '日期不合法哦'
  34. }
  35. ]
  36. let {stateData} = this.state
  37. //遍历数据 返回提示
  38. msgGroup.some((v) => {
  39. if(v.validate ? v.validate(stateData, v.key) : !stateData[v.key]) {
  40. data = {
  41. msg: v.msg,
  42. el: getEl[v.el||0](v.key)
  43. }
  44. return true
  45. }
  46. })
  47. return data
  48. }
  49. //错误信息提示
  50. showWarn(el) {
  51. let className = el.className
  52. if(el.getAttribute('isWarn')) {
  53. return
  54. }
  55. el.setAttribute('isWarn', '1')
  56. el.className = className + ' ui--error'
  57. el.scrollIntoView()
  58. setTimeout(function() {
  59. el.className = className
  60. el.setAttribute('isWarn', '')
  61. }, 3000)
  62. }
  63. //提交表单 触发验证
  64. onSave =()=>{
  65. var data = this.validate()
  66. if(data.msg) {
  67. message.error(data.msg, 3)
  68. data.el && this.showWarn(data.el)
  69. return
  70. }
  71. ajax.post('xxxx')
  72. }
  73. //render
  74. <Input
  75. className="item-input"
  76. placeholder="请输入11位数字"
  77. maxLength="11" type="phone"
  78. ref="tenantPhone"
  79. value={tenantPhone||undefined}
  80. onChange={
  81. e => this.setState({
  82. tenantPhone: e.target.value
  83. })
  84. }
  85. onBlur={() => {
  86. if(!/^1[345678]\d{9}$/.test(tenantPhone)) {
  87. if(!tenantPhone) {
  88. message.error('手机号不可为空!')
  89. return
  90. }
  91. message.error('手机号不合法哦')
  92. }
  93. }}
  94. />

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/115575
推荐阅读
相关标签
  

闽ICP备14008679号