最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Textfields component number validation React js - Stack Overflow

programmeradmin0浏览0评论

I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

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>
    );
  }
}

Can someone help me on this please.

Thanks in advance.

I have 3 Textfields, what I want to do is just to accept number so if someone put text and click continue the application should display an error saying that just numbers are allowed.

The following code displays an error message if the Textfield is empty and thats ok but the other validation to check if the user inputs text or numbers is pending and I'm stucked.

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>
    );
  }
}

Can someone help me on this please.

Thanks in advance.

Share Improve this question asked Dec 6, 2017 at 5:55 kennechukennechu 1,4229 gold badges25 silver badges37 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

You can prevent users from input text by using this :

<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"
/>

The TextField ponent can restrict users to entering text using the JavaScript test method:

<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"
/>

Try adding this code in your validate function.

You can use regex to validate your fields for text or numbers like :

  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;
  }

In RegexExpression file add these validations like this :

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

You are not initialising error object in state but accessed in TextField as this.state.and_error. Either you should initialise error in constructor like this.state = { and_error: "" } or initialise error object as

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

So in your 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"
/>

Your validate function will be like

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;
}

Hope this will heps you!

You can use react-validation for all validation and set rules for validation

发布评论

评论列表(0)

  1. 暂无评论