一个表单验证例子

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script src="test/react.js"></script>
    <script src="test/react-dom.js"></script>
    <script src="test/babel.js"></script>
</head>

<body>

    <div>这个默认会被清掉</div>
    <div id='example'></div>
    <pre>
      
    </pre>

    <script type='text/babel'>
    var container = document.getElementById("example")
    var div = container
    var styles = {}

    class Envvar extends React.Component {
        constructor(a){
          super(a)
          this.nodesToValidate = []
          this.state = {
            data:this.props.data
          }
        }
        additem() {
           let data = this.state.data
           data.push({})
           this.setState({
              data
            })
          
        }
        subtractitem(i){
          //删除数组的某一位
           let data = this.state.data

           data.splice(i,1)
           this.setState({
              data
            })
          
        }
        onSubmit(event){//验证列队中所有的元素, onSubmit事件必须放在form元素上
           var elems = this.nodesToValidate
           if(elems.length === 0){
               event.preventDefault() 
               alert("没有输入任何数据")
               return
           }
           for(var i =0 ,n = elems.length; i < n; i++){
               if(this.validate(elems[i]) === false){//如果有一个不通过
                   event.preventDefault() //阻止默认行为,不提交
                   break
               }
           }
        }
        onChange(i, props, event ){
            var data = this.state.data
            var target = event.target;
            data[i][props] = target.value //更新data
            this.setState({ //更新UI
                data: data
            })
            var index = this.nodesToValidate.indexOf(target)
            if(index === -1){ //决定是否放进列队
                this.nodesToValidate.push(target)
            }
            return this.validate(target) //验证
        }
        
        validate(target){//验证当个元素
           var regexp = target.regexp //ref方法里面加你喜欢的正则
            if(!regexp){ //没有正则当作成功
               return true
            }
            if(!regexp.test(target.value)){
                target.style.color = "red"//加红
                target.scrollIntoView()  //滚动
                return false //失败
            }else{
                target.style.color = "black"
                return true  //成功
            }
        }
        render() {
          let data = this.state.data;
          return (
          <form className={styles.Envvar} onSubmit={this.onSubmit.bind(this)}>
          <label>环境变量</label>
          <div>
          { data.map((item,i)=>{
          if(item){     
           return (<div className={styles.Envvarconf} key={i}>
               <input type="text" name="key"   
                  placeholder="key" 
                  value={this.state.data[i]["key"]||''}
                  ref={(dom)=>{ if(dom){ dom.regexp = /^[a-z]+$/i }  }} 
                  onChange={this.onChange.bind(this, i, "key" )} />
              <input type="text" name="value" 
                 placeholder="value"  
                 value={this.state.data[i]["value"]||''} 
                 onChange={this.onChange.bind(this, i, "value" )} />
             { i== 0 ?  <span onClick={()=>this.additem()}>+</span> :
                <span onClick={()=>this.subtractitem(i)}>-</span>
             }
           </div>)
           }
          })
            }
              </div>
              <p><button type="submit" >提交</button></p>
          </form>
          )
        }
      }
      Envvar.defaultProps = {
        data:[{key:'',value:''}]
      };
 
 var s = ReactDOM.render(<Envvar />, div, function(){
        console.log("done!")
 });
 
      </script>
</body>

</html>
    原文作者:司徒正美
    原文地址: https://segmentfault.com/a/1190000011939273
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞