2017-01-18 51 views
1

我正在設計一個包含複選框和單選按鈕的應用程序。如何驗證redux表單中的單選按鈕值?

有三個單選按鈕放在三個不同的組件中。如下所示,我想驗證任何這些單選按鈕(或選項)是否被選中。如何實現這一目標? (我使用Redux的形式6.4.3)

Radio1.js

Import { Field } from 'redux-form'; 
    class radio1 extends react.component { 

    render() { 

     return ( 
      <tr> 
       <td> 
       <table> 
        <tbody> 
        <tr> 
         <td> 
          <Field component={renderInput} type="radio" value="radio1" /></td> 
         <td>This is radio button 1</td> 
        </tr> 
       </tbody> 
       </table> 
      </td> 
      <tr> 
     ) 
     } 
    } 
export default radio1; 

Radio2.js

Import { Field } from 'redux-form'; 
class radio2 extends react.component { 

render() { 

    return ( 
     <tr> 
      <td> 
       <table> 
        <tbody> 
         <tr> 
         <td> 
          <Field component={renderInput} type="radio" value="radio2" /></td> 
           <td>This is radio button 2</td> 
         </tr> 
        </tbody> 
       </table> 
       </td> 
       </tr> 
    ) 
    } 
} 
export default radio2; 

Radio3.js

Import { Field } from 'redux-form'; 
class radio3 extends react.component { 

render() { 

    return ( 
     <tr> 
      <td> 
      <table> 
       <tbody> 
        <tr> 
        <td> 
         <Field component={renderInput} type="radio" value="radio3" /></td> 
          <td>This is radio button 3</td> 
        </tr> 
       </tbody> 
       </table> 
      </td> 
      </tr> 
    ) 
    } 
} 
export default radio3; 

renderInput.js

 const renderInput= ({input, placeholder, defaultValue, meta: {touched, error, warning}}) =>   
     <div> 
      <input {...input} type={type} /> 
     </div> 
); 

export default renderInput; 

Main.js

import radio1 from './radio1'; 
import radio2 from './radio2'; 
import radio3 from './radio3'; 

class Main extends React.Component { 

render() { 
return (
<table> 
<tbody> 
<radio1 /> 
<radio2 /> 
<radio3 /> 
</tbody> 
</table> 

) 

} 

} 

export default Main; 

回答

-1

Field組分具有validate道具。您可以通過一個函數,將在文檔驗證值

function validateRadio(value) { 
    if(!value) { 
    return 'You need to check this value' 
    } 
} 
<Field component={renderInput} type="radio" value="radio3" validate={validateRadio} /> 

相關部分:http://redux-form.com/6.4.3/docs/api/Field.md/