Textfields组件编号验证React js

时间:2017-12-06 05:55:07

标签: javascript reactjs material-ui

我有3个文本字段,我想要做的只是接受数字,所以如果有人放置文本并单击继续,应用程序应显示错误,说明只允许数字。

以下代码显示错误消息,如果Textfield为空且没关系,但另一个验证用于检查用户输入的文本或数字是否处于待处理状态且我被卡住了。

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';

import cr from '../styles/general.css';


export default class Example extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      buy_: '',
      and_: '',
      save_: '',

    };
    this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event, index, value) {
    this.setState({value});
  }



  clear() {
    console.info('Click on clear');
    this.setState({
      buy_: '',
      and_: '',
      save_: ''
    });
  }

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_.length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }
    if (this.state.and_.length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }
    if (this.state.save_.length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

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

    return isError;
  }

  onSubmit(e){
    e.preventDefault();
    // this.props.onSubmit(this.state);
    console.log('click onSubmit')
    const err = this.validate();
    if (!err) {
      // clear form
      this.setState({
        buy_error: '',
        and_error: '',
        save_error: ''
      });
      this.props.onChange({
        buy_: '',
        and_: '',
        save_: ''
      });
    }
  }

  render() {


    return (
      <div className={cr.container}>
        <div className ={cr.boton}>
          <Divider/>
          <br/>
        </div>

        <div className={cr.rows}>
          <div>
            <TextField
              onChange={(e) => {this.setState({buy_: e.target.value})}}
              value={this.state.buy_}
              errorText={this.state.buy_error}
              floatingLabelText="Buy"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({and_: e.target.value})}}
              value={this.state.and_}
              errorText={this.state.and_error}
              floatingLabelText="And"
            />
          </div>
          <div>
            <TextField
              onChange={(e) => {this.setState({save_: e.target.value})}}
              value={this.state.save_}
              errorText={this.state.save_error}
              floatingLabelText="Save"
            />
          </div>
        </div>

        <div className={cr.botonSet}>
          <div className={cr.botonMargin}>
            <RaisedButton
              label="Continue"
              onClick={e => this.onSubmit(e)}/>
          </div>
          <div>
            <RaisedButton
              label="Clear"
              secondary ={true}
              onClick={this.clear = this.clear.bind(this)}
            />
          </div>
        </div>
      </div>
    );
  }
}

请有人帮我解决这个问题。

提前致谢。

5 个答案:

答案 0 :(得分:1)

您可以使用以下方法阻止用户输入文本:

<TextField 
    onChange={(e) => {  
        if(e.target.value === '' || /^\d+$/.test(e.target.value)) { 
            this.setState({and_: e.target.value})
        } else { 
            return false; 
        } 
    }}
    value={this.state.and_}
    errorText={this.state.and_error}
    floatingLabelText="And"
/>

答案 1 :(得分:1)

TextField组件可以限制用户使用JavaScript test方法输入文本:

<TextField
  onChange={(e) => {
     if(e.target.value == '' || (/\D/.test(e.target.value))) {
         this.setState({and_: e.target.value})}
     }
     else {
         return false;
     }
  }
  value={this.state.and_}
  errorText={this.state.and_error}
  floatingLabelText="And"
/>

答案 2 :(得分:0)

您没有在state初始化错误对象,而是在TextField中以this.state.and_error进行访问。您应该在this.state = { and_error: "" }之类的构造函数中初始化错误,或者将error对象初始化为

this.state = { 
    error: { 
       and_error: "",
       buy_error: "",
       save_error: "" 
    } 
}

所以在TextField

<TextField
      onChange={(e) => {
        if(e.target.value === "" || (/\D/.test(e.target.value))) {
           this.setState({and_: e.target.value})}
        }
        else {
          return false;
        }
      }
      value={this.state.and_}
      errorText={this.state.error.and_error} // If initialised error string access as this.state.and_error
      floatingLabelText="And"
/>

您的验证功能将类似于

validate() {
    let isError = false;
    const errors = this.state.errors;

    if (this.state.buy_.toString().length < 1 || this.state.buy_ === null) {
      isError = true;
      errors.buy_error = 'Field requiered';
    }

    if (this.state.and_.toString().length < 1 || this.state.and_ === null) {
      isError = true;
      errors.and_error = 'Field requiered';
    }

    if (this.state.save_.toString().length < 1 || this.state.save_ === null) {
      isError = true;
      errors.save_error = 'Field requiered';
    }

    this.setState({errors});

    return isError;
}

希望这能帮助你!

答案 3 :(得分:0)

尝试在验证功能中添加此代码。

您可以使用正则表达式验证字段中的文本或数字,如:

  import * as RegExp from './RegExpression';

  validate() {
    let isError = false;
    const errors = {
      descriptionError: ''
    };

    if (this.state.buy_ && !RegExp.NAME.test(this.state.buy_)) {
      // validation check if input is name
      isError = true;
      errors.buy_error = 'Invalid name';
    }
    if (this.state.and_ && !RegExp.NUMBER.test(this.state.and_)) {
      // validation check if input is number
      isError = true;
      errors.and_error = 'Invalid Number';
    }

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

    return isError;
  }

在RegexExpression文件中添加以下验证:

 export const NAME = /^[a-z ,.'-()"-]+$/i;
 export const NUMBER = /^[0-9]*$/ ;

答案 4 :(得分:0)

您可以对所有验证使用反应验证并设置验证规则