HelpBot Assistant

How can I help you?

Change the color of the TextBox based on its value in React TextBox component

21 Feb 20265 minutes to read

Dynamically update the TextBox appearance based on user input by validating the value using regular expressions in the keyup event. This provides immediate visual feedback about input validity. The following example demonstrates changing the TextBox color when numeric values are detected.

import * as React from "react";
import * as ReactDOM from "react-dom";
import { TextBoxComponent } from "@syncfusion/ej2-react-inputs";
export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.onKeyup = this.onKeyup.bind(this);
    }
    onKeyup(e) {
        const str = e.target.value.match(/^[0-9]+$/);
        if (!((str && str.length > 0)) && e.target.value.length) {
            e.target.parentNode.classList.add('e-error');
        }
        else {
            e.target.parentNode.classList.remove('e-error');
        }
    }
    render() {
        return (<div className="wrap">
            <label> Normal Input </label>
                <TextBoxComponent  id="numericOnly" placeholder="Enter numeric values" onKeyUp={this.onKeyup}/>
            <label> Floating Input </label>
                <TextBoxComponent placeholder="Enter numeric values" floatLabelType="Auto" onKeyUp={this.onKeyup} required = {true}/>
            </div>);
    }
}
;
ReactDOM.render(<App />, document.getElementById('input-container'));
import * as React from "react";
import * as ReactDOM from "react-dom";
import { TextBoxComponent } from "@syncfusion/ej2-react-inputs";
export default class App extends React.Component<{}, {}> {
        constructor(props: any) {
            super(props);
            this.onKeyup = this.onKeyup.bind(this);
        }
    public onKeyup(e: React.KeyboardEvent) {
      const str = (e.target as HTMLInputElement).value.match(/^[0-9]+$/);
      if (!((str && str.length > 0)) && (e.target as HTMLInputElement).value.length) {
        ((e.target as HTMLInputElement).parentNode as HTMLElement).classList.add('e-error');
      } else {
        ((e.target as HTMLInputElement).parentNode as HTMLElement).classList.remove('e-error');
      }
    }

        public render() {
        return (
            <div className="wrap">
            <label> Normal Input </label>
                <TextBoxComponent  id="numericOnly" placeholder="Enter numeric values" onKeyUp={this.onKeyup}/>
            <label> Floating Input </label>
                <TextBoxComponent placeholder="Enter numeric values" floatLabelType="Auto" onKeyUp={this.onKeyup} required = {true}/>
            </div>
        )
    }
};
ReactDOM.render(<App />, document.getElementById('input-container'));