我使用React js和Material-UI。如何在按钮提交点击上验证“正确”的绿色验证?

时间:2017-09-05 16:32:49

标签: reactjs material-ui

帮助,请。我使用React js和Material-IU。我使用errorText进行了“不正确”的红色文本字段验证。如何在按钮提示点击上验证绿色的“正确”?

validate = () => {  
  const cardNumber = '1234567890123456'; //credit card form with 2 fields
  const expiryNumber = '1234';
  let isError = false;
  const errors = {};

  if (this.state.number != cardNumber) { //cardNumber validation
    isError = true;
    errors.numberError = 'failed';
    }

  if (this.state.expiry != expiryNumber) { //expiry validation
    isError = true;
    errors.expiryError = "failed";
    }

  if(isError) {
    this.setState({
        ...this.state,
        ...errors
    });
    }

  return isError;
  }


onSubmit = e => {    // on Button submit   
  e.preventDefault();
  const err = this.validate();
  if (!err) {
    this.setState({
      number: "",
      expiry: ""
      });
    console.log(this.state);
    };
  }    // next will be render <TextField>    

1 个答案:

答案 0 :(得分:2)

我尝试在组件状态successValidation中使用额外字段,我根据验证结果更改onSubmit。然后我使用该state属性来确定要传递给underlineStyle的样式(TextField的属性)。也许不是最干净的解决方案(不知道),但据我所知,它可行。您可以在this JSFiddle demo中看到它。

顺便说一下:我使用Material-UI已经有一段时间了,但是他们有很好的文档来刷新你的记忆。例如,您可以在this page底部看到TextField的所有道具。

const { RaisedButton, MuiThemeProvider, getMuiTheme, TextField } = MaterialUI;

 class Test extends React.Component {

  state = {
    value: 'good',
    error: false,
    successValidation: false
  }

  handleInputChange = (e, newValue) => {
    // reset errors and validation as well
    this.setState({
        value: newValue, 
      error: false,
      successValidation: false
     });
  }

  isValid = () => {
    const {value} = this.state;
    return value != 'bad';
  }

  onSubmit = () => {
    if(this.isValid()) {
        this.setState({successValidation: true, error: false});
    } else {
        this.setState({error: true});
    }

  }

  render = () => {
    const {value, error, successValidation} = this.state;
    const underlineStyle = successValidation ? { borderColor: 'green' } : null;
    return (
      <div style={{width: '50%', margin: '0 auto'}}>
        <h3>The input "bad" will cause error</h3>
        <h3>All other input will cause green underline on submit</h3>
        <TextField 
          errorText={error ? 'Validation error!' : ''}
          name="test" 
          value={value} 
          onChange={ this.handleInputChange }
          underlineStyle={underlineStyle}
         />
        <RaisedButton onClick={ this.onSubmit }>Submit</RaisedButton>
      </div>
    );
  }

}

const App = () => (
  <MuiThemeProvider muiTheme={getMuiTheme()}>
    <Test />
  </MuiThemeProvider>
);

ReactDOM.render(
  <App />,
  document.getElementById('container')
);