2017-03-02 102 views
0

我有以下的JSON在它動態表單驗證

const BILL_NUMBER = [ 
{ 
    "caseIndex": "Bill Number", 
    "minLength":"3", 
    "maxLength": "16", 
    "htmlControlType": "text", 
    "errorMessage": "Alphanumeric Only", 
    "idxReglrExp":"^[a-zA-Z0-9_\\s]*$", 
    "cssClassName":"form-control" 
} 
]; 
下面

的所有字段屬性是呈現JSON數據的功能和領域是越來越顯示在頁面

renderBillNumber: function() { 

    const data = BILL_NUMBER; 
    return data.map(group => { 
     return <div> 
       <label for="billnumber">{group.caseIndex}</label> 
            <input type={group.htmlControlType} className={group.cssClassName} id="billnumber" placeholder=""/> 
            </div> 
    }); 

}, 

我想驗證這個字段與來自JSON的屬性,如minlength,maxlength,並顯示基於正則表達式的錯誤消息。

任何人都可以幫助我如何在reactjs中做到這一點?

回答

0

您需要添加一個onChange屬性,將做檢查爲您提供:

renderBillNumber: function() { 
    const data = BILL_NUMBER; 
    return data.map(group => 
    <div> 
     <label for="billnumber">{group.caseIndex}</label> 
     <input 
     onChange={(e) => this.handleChange(e, group)} 
     type={group.htmlControlType} 
     className={group.cssClassName} 
     /> 
    </div> 
    }); 
}, 
handleChange(event, group) { 
    const value = event.target.value; 
    if (value.length < group.minLength) { 
    // do what you want to do if value is too small 
    } 
    // all you want to check 
} 
0

爲了做到這一點,您將不得不跟蹤每個輸入的狀態。如果這裏的想法是您的JSON中會有X數量的賬單號碼,那麼只記錄那些在您的狀態中存在錯誤的賬號可能是有意義的。

你可能會首先創建一個驗證功能,像這樣:

validateText(evt){ 
// Get the current user input for this input box 
const userInput = evt.target.value; 

// Grab the current errors state 
const errors = this.state.errors || {}; 

// Cycle through your JSON to get the data you need 
BILL_NUMBER.forEach(bill => { 

    // If this is the right bill, then get the validation data we need. 
    if (bill.caseIndex === evt.target.name){ 
     const minLength = bill.minLength; 
     const maxLength = bill.maxLength; 
     const re = bill.idxReglrExp; 
     if (userInput.length >= minLength && 
      userInput.length <= maxLength && 
      userInput.match(re)){ 
       //We're valid - cycle through state & remove error if it's there. 
     } else { 
      // Add this caseIndex to your state: 
      this.setState({ 
       errors: { 
        ...errors, 
        bill.caseIndex: true 
       } 
      }); 
     } 
    } 
}); 

},

然後,您可以編輯您renderBillNumber功能,使你的函數被調用,只要用戶輸入文本。此外,您可以添加一個「名稱」屬性,指向您的輸入,或類似地assign a ref

renderBillNumber: function() { 

const data = BILL_NUMBER; 
return data.map(group => { 
    if (this.state.errors[caseIndex]){ 
     return (
      <div>error</div> 
     ); 
    } 
    return (
     <div> 
      <label for="billnumber">{group.caseIndex}</label> 
      <input name={group.caseIndex} onInput={this.validateText} type={group.htmlControlType} className={group.cssClassName} id="billnumber" placeholder=""/> 
     </div> 
    ) 
}); 

}

這樣,當用戶輸入什麼validateText將被調用。如果狀態發生變化,您的賬單將通過適當的視覺材料重新渲染。