Hooks 简易表单验证

import React from 'react'
import {
  Form, 
  Icon, 
  Input, 
  Button, 
  Row, 
  Col, 
  message,
  Select
 } from 'antd'
import { useRef, useState } from 'react'
import './style.scss';

const { Option } = Select;
const HooksForm = () =>{
  const [val,setVal] = useState({
    phone:'',
    name:'',
    selectColor:'Red'
  })
  const phoneRef = useRef()
  const nameRef = useRef()
  const selectRef = useRef()
  const handleSubmit =(e)=>{ 
    let data = validate()
    console.log('>>>>>>>>>>>', data)
    if(data.msg) {
      message.error(data.msg, 3)
      data.el && showWarn(data.el)
      return
    }
  }

  const validate =()=>{
    let data = {
      msg: '',
      el: null
    }

    let msgGroup = [
      {
        key:'phone',
        msg:'手机号',
        validate:function(data,key){
          let val = data[key]
          if(!/^1[345678]\d{9}$/.test(val)) {
            return true
          }
        },
        refs:phoneRef
      },
      {
        key:'name',
        msg:'名称',
        refs:nameRef
      },
      {
        key:'selectColor',
        msg:'select',
        refs:selectRef
      }
    ]

    msgGroup.some(v => {
      if(v.validate ? v.validate(val, v.key) : !val[v.key]) {
        console.log('val >>>>>>>>>>>', val)
        data = {
          msg: v.msg,
          el: v.refs.current.input || v.refs.current.rcSelect.rootRef 
        }
        return true
      }
      return null
    })
    return data
  };

  function showWarn(el) {
    let className = el.className
    console.log('className:',className);
    if(el.getAttribute('isWarn')) {
      return
    }
 
    el.setAttribute('isWarn', '1')
 
    el.className = className + ' ui--error'
    el.scrollIntoView()
    setTimeout(function() {
      el.className = className
      el.setAttribute('isWarn', '')
    }, 3000)
  };
  return (
    
phone: } placeholder="填写手机号" maxLength={11} ref={phoneRef} value={val.phone} name="phone" onChange={e=>setVal({ ...val, phone: e.target.value })} /> name: } type="text" placeholder="填写名称" ref={nameRef} value={val.name} name="name" onChange={e=>setVal({ ...val, name: e.target.value })} /> password:
) } export default HooksForm

效果:

Hooks 简易表单验证_第1张图片 Hooks 简易表单验证_第2张图片Hooks 简易表单验证_第3张图片

Hooks 简易表单验证_第4张图片

附:react+antd 简单表单验证

你可能感兴趣的:(js)