Ads Top

How to validate input field in react js?

React form validation example(POC): Here example is showing only one fields for the validation if we will click directly on “add goal” button then our heading text will be red and input fields will be border black and background color red. We can do with help of JavaScript code and CSS.

 

We can see below code:-

app.js

import 'bootstrap/dist/css/bootstrap.min.css'
import GoalData from './components/goal/goalData';

function App() {
  return (
    <>
      <GoalData />
    </>
  );
}

export default App;

goaldata.js

import { useState } from "react"
import Goalform from "./goalform"
import Goalsec from "./goalsec"

export default () => {

    const goalListsAll = [
        { goalName: 'Finish the course' },
        { goalName: 'completed react course' },
    ]

    const [addedGoal, setAddedGoal] = useState(goalListsAll);
    const newGoalHandler = (goal) => {
        return setAddedGoal((preGoal) => {
            return [goal, ...preGoal]
        })
    }

    return (
        <>
            <Goalform onAddNewGoalHandler={newGoalHandler} />
            <Goalsec goalLists={addedGoal} />
        </>
    )
}

goalsec.js

import './goalform.css';

export default ({ goalLists }) => {

    const renderGoalList = () => {
        return goalLists.map((item) =>
            <div className="goalSection" key={Math.random().toFixed(10)}>
                {item.goalName}
            </div>
        )
    }
    return (
        <>
            {renderGoalList()}
        </>
    )
}

goalform.scss

.goalForm{
    padding20px;
    border1px solid #ccc;
    box-shadow0 0 20px 0 #aaa;
    max-width500px;
    margin50px auto 20px;
    border-radius10px;
    &.invalid{
        label{
            color#f00;
        }
        input{
            border-color#000;
            background#f00
        }
    }
}
/* .goalForm.invalid label{
    color: #f00;
.goalForm.invalid input{
    border-color: #000;
    background: #f00;
}*/
.goalSection{    margin10px auto;
    max-width500px;
    background#f5f5f5;
    padding10px;
    border-radius5px;
    font-weight700;
    font-size18px;}

Very important things is we can do with style and class.

React field validation with style example:

goalform.js

import { useState } from 'react'
import './goalform.css'
export default ({ onAddNewGoalHandler }) => {

    const [enterdGoal, setEnterdGoal] = useState('');
    const [isValid, setIsValid] = useState(true);

    const goalTextHandler = (event) => {
        if (enterdGoal.trim().length > 0) {
            setIsValid(true);
        }
        setEnterdGoal(event.target.value);
    }

    const formChangeHandler = (event) => {
        event.preventDefault();
        if (enterdGoal.trim().length === 0) {
            setIsValid(false);
            return;
        }
        let formData = {
            goalName: enterdGoal,
        }
        onAddNewGoalHandler(formData);
    }

    return (
        <>
            <div className="container">
                <div className="row">
                    <form className="goalForm" onSubmit={formChangeHandler}>
                        <div className="mb-3">
                            <label className="form-label" 
                            style={{color: !isValid ? 'red' : 'black'}}>
                                Course Goal</label>
                            <input type="text" 
                            value={enterdGoal} 
                            onChange={goalTextHandler} 
                            className="form-control"
                            style={{background: !isValid ? 'red' : 'transparent'
                            borderColor: !isValid ? 'black' : '#ccc'}} />
                        </div>
                        <button type="submit" 
                        className="btn btn-primary">Add Goal</button>
                    </form>
                </div>
            </div>
        </>
    )
}

React field validation with class example:

goalform.js

import { useState } from 'react'
import './goalform.css'
export default ({ onAddNewGoalHandler }) => {

    const [enterdGoal, setEnterdGoal] = useState('');
    const [isValid, setIsValid] = useState(true);

    const goalTextHandler = (event) => {
        if (enterdGoal.trim().length > 0) {
            setIsValid(true);
        }
        setEnterdGoal(event.target.value);
    }

    const formChangeHandler = (event) => {
        event.preventDefault();
        if (enterdGoal.trim().length === 0) {
            setIsValid(false);
            return;
        }
        let formData = {
            goalName: enterdGoal,
        }
        onAddNewGoalHandler(formData);
    }

    return (
        <>
            <div className="container">
                <div className="row">
                    <form className={`goalForm ${!isValid ? 'invalid' : ''}`} 
                    onSubmit={formChangeHandler}>
                        <div className="mb-3">
                            <label className="form-label">
                                Course Goal</label>
                            <input type="text"
                                value={enterdGoal}
                                onChange={goalTextHandler}
                                className="form-control" />
                        </div>
                        <button type="submit" 
                        className="btn btn-primary">Add Goal</button>
                    </form>
                </div>
            </div>
        </>
    )
}

Your result will be below as screenshot:

No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.