一個表單驗證例子

<!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>
相關文章
相關標籤/搜索