kennechu
kennechu

Reputation: 1422

Textfields component number validation React js

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.

Upvotes: 1

Views: 4892

Answers (5)

Javad Khodadadi
Javad Khodadadi

Reputation: 408

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

Upvotes: 0

Elumalai Kaliyaperumal
Elumalai Kaliyaperumal

Reputation: 1520

The TextField component 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"
/>

Upvotes: 1

user9060137
user9060137

Reputation: 1

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!

Upvotes: 0

Shivani
Shivani

Reputation: 350

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]*$/ ;

Upvotes: 0

Sagar Jajoriya
Sagar Jajoriya

Reputation: 2375

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

Upvotes: 3

Related Questions