0

I know there are many articles out there on validation but I haven't found any solution for my case. I just have one input text and want to validate it, but didn't make any progress. Validation must be in react. Please help me in making it or guide me.

var styles = {
  margin: '2em auto',
  width: '300px',
  height: '300px',
  backgroundColor: '#DD4814',
  color: '#ffffff',
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'space-around'
};
var inputs = {
  position: 'relative',
  bottom: '17%',
  left: '20%'
}
var btns = {
  position: 'relative',
  bottom: '7%'
}
var btn = {
  backgroundColor: '#ffffff',
  color: '#000000',
  borderColor: '#DEB887',
  borderRadius: '0.4em',
  cursor: 'pointer',
  margin: '0 1em',
  padding: '0.5em',
  display: 'inline-block'
}
class Timer extends React.Component {
  constructor (props) {
    super(props)
    this.state = {count: 0, customNumber: 0}
  }
  handleChange (e) {
    this.setState({ customNumber: e.target.value});
  }
  componentWillUnmount () {
    clearInterval(this.timer)
  }
  tick () {
    if (this.state.customNumber) {
      this.setState({
        count: (this.state.customNumber--)
      })
      if (this.state.customNumber <= 0) {
        this.setState({ count: 0})
        clearInterval(this.timer)
        this.setState( {disabled: !this.state.disabled} )
      }
    } else {
      this.setState({count: (this.state.count + 1)})
    }
  }
  
  display () {
    return ('0' + this.state.count % 100).slice(-2)
  }
  
  startTimer () {
    clearInterval(this.timer)
    this.timer = setInterval(this.tick.bind(this), 1000)
    this.setState( {disabled: !this.state.disabled} )
  }
  stopTimer () {
    clearInterval(this.timer)
  }
  resetTimer () {
    clearInterval(this.timer)
    this.setState({count: 0})
    this.setState( {disabled: !this.state.disabled} )
  }
  render () {
    return (
      <div style={styles} className='timer'>
        <h1 style={{fontSize: '4em'}}>{this.display()}</h1>
        <div className="input_text" style={inputs}>
          <label htmlFor="custom_number">Enter number to start timer</label>
          <input type="text" name="custom_number" id="custom_number" value={this.state.inputValue} onChange={this.handleChange.bind(this)} disabled = {(this.state.disabled)? "disabled" : ""}  placeholder="Enter b/w 1-100" />
        </div>
        <div style={btns} className="buttons">
          <button style={btn} type="button" name="start_btn" id="start_btn" onClick={this.startTimer.bind(this)}>Start</button>
          <button style={btn} type="button" name="stop_btn" id="stop_btn" onClick={this.stopTimer.bind(this)}>Pause</button>
          <button style={btn} type="button" name="reset_btn" id="reset_btn" onClick={this.resetTimer.bind(this)}>Stop</button>
        </div>
      </div>
    )
  }
}
ReactDOM.render(<Timer />, document.getElementById('root') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

3
  • You can try following this: learnetto.com/blog/how-to-do-simple-form-validation-in-reactjs A pretty easy read Commented Sep 17, 2017 at 17:27
  • You need to use this.setState in your handleChange function. Commented Sep 17, 2017 at 17:54
  • In HandleChange you have an input value. So you can validate it as you want (length, email etc). Commented Sep 17, 2017 at 19:01

1 Answer 1

1

Example of simple validation in your case:

class Timer extends React.Component {
 constructor (props) {
   super(props)
   this.state = {count: 0, customNumber: 0, error: {}}
 }
 handleChange (e) {
  const error = {};
  if(parseInt(e.target.value) === 'NaN') { // your validation rules here...
   error.customNumber = { title: 'Custom number error!', msg: 'Something wrong with your input value' }
  }
  this.setState({ customNumber: e.target.value, error });
 }
 componentWillUnmount () {
  clearInterval(this.timer)
 }
 tick () {
   if (this.state.customNumber) {
    this.setState({
    count: (this.state.customNumber--)
   })
   if (this.state.customNumber <= 0) {
    this.setState({ count: 0})
    clearInterval(this.timer)
    this.setState( {disabled: !this.state.disabled} )
   }
  } else {
   this.setState({count: (this.state.count + 1)})
  }
 }

 display () {
  return ('0' + this.state.count % 100).slice(-2)
 }

 startTimer () {
  clearInterval(this.timer)
  this.timer = setInterval(this.tick.bind(this), 1000)
  this.setState( {disabled: !this.state.disabled} )
}
stopTimer () {
 clearInterval(this.timer)
}
resetTimer () {
 clearInterval(this.timer)
 this.setState({count: 0})
 this.setState( {disabled: !this.state.disabled} )
}
render () {
 const { error } = this.state;  
 return (
   <div style={styles} className='timer'>
    <h1 style={{fontSize: '4em'}}>{this.display()}</h1>
    <div className={`input_text ${error.customNumber ? 'has-error' : ''} `} style={inputs}>
      <label htmlFor="custom_number">Enter number to start timer</label>
      <input type="text" name="custom_number" id="custom_number" value={this.state.inputValue} onChange={this.handleChange.bind(this)} disabled = {(this.state.disabled)? "disabled" : ""}  placeholder="Enter b/w 1-100" />
    </div>
    <div style={btns} className="buttons" disabled={!isEmpty(error)}>
      <button style={btn} type="button" name="start_btn" id="start_btn" onClick={this.startTimer.bind(this)}>Start</button>
      <button style={btn} type="button" name="stop_btn" id="stop_btn" onClick={this.stopTimer.bind(this)}>Pause</button>
      <button style={btn} type="button" name="reset_btn" id="reset_btn" onClick={this.resetTimer.bind(this)}>Stop</button>
    </div>
  </div>
  )
 }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Not working throwing error of and "isEmpty is not defined".
isEmpty it is lodash function, i write it as example, you can use another library if you want. So if you wont to use lodash you need to install the library npm install --save lodash, then you can import it: import isEmpty from 'lodash/isEmpty', and use it, it's easy.
any alternative of isEmpty? if no it means that i cannot validate a form without any extra library.
No you can ofcourse, simple example of alternative isEmpty: Object.keys(error).length <= 0, or in your case: disabled={Object.keys(error).length <= 0}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.