2017-07-14 87 views
2

爲什麼setCustomValidity()在React中不起作用?我錯過了什麼嗎?香草HTML和JS工作正常。或者有其他方法可以輕鬆地做出類似於setCustomValidity的東西嗎?爲什麼setCustomValidity()在React應用程序中不起作用?

陣營代碼:

class Form extends React.Component { 
    formVal(e) { 
    e.target.setCustomValidity("Test_1"); 
    } 
    formVal2() { 
    let inpt = document.getElementById("input"); 
    inpt.target.setCustomValidity("TEST_2"); 
    } 
    render() { 
    return (
     <div> 
     <form> 
      <input 
      id="input" 
      type="datetime-local" 
      onBlur={this.formVal} 
      /> 
     </form> 
     <button onClick={this.formVal2}>Click </button> 
     </div> 
    ); 
    } 
} 

CodePen - React

在沒有陣營:

<form> 
    <input type="email" id="mail" name="mail"> 
    <button onclick="test()">Submit</button> 
</form> 

// JS

​​

CodePen - no React

+1

檢查功能formVal2,你不需要'.target' – Mikalai

+0

@Mikalai你是對的,但仍然沒有工作。通過'document.getElementById()'獲取元素不是在React中推薦的。 – KATq

回答

1

setCustomValidity不會立即觸發驗證,您必須有表單提交事件才能觸發它或致電checkValidity。我已更新您的CodePen以顯示您如何在React中實現此目標,並且它也包含在下面。

class Form extends React.Component { 
 
    
 
    onChange(e) { 
 
    let date = new Date(Date.parse(e.target.value)); 
 
    
 
    if (date > new Date()) { 
 
     e.target.setCustomValidity("Please select a date in the past."); 
 
    } else { 
 
     e.target.setCustomValidity(""); 
 
    } 
 
    } 
 
    
 
    render() { 
 
    return (
 
     <div> 
 
     <form> 
 
      <input 
 
      id="input" 
 
      type="datetime-local" 
 
      onChange={this.onChange} 
 
      /> 
 
      <button type="submit">Submit</button> 
 
     </form> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(<Form />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="root"></div>

相關問題