score:0

Accepted answer

i suggest to add state property called submitted when it's true it allows the errors show and also watch the input values to fill the errors :

import react from 'react';

const untitled = () => {
    const [name, setname] = react.usestate('');
    const [email, setemail] = react.usestate('');
    const [errors, seterrors] = react.usestate < any > {};
    const [submitted, setsubmitted] = react.usestate(false);
    function handlesubmit() {
        setsubmitted(true);
    }

    react.useeffect(() => {
        let newerrors = {};

        if (name.trim() === '' && submitted) {
            newerrors = { ...newerrors, name: 'name cannot be empty' };
        } else if (name.trim().length < 3) {
            newerrors = {
                ...newerrors,
                name: 'name length cannot be less than 3 characters',
            };
        }

        if (email.trim() === '' && submitted) {
            newerrors = { ...newerrors, email: 'email cannot be empty' };
        } else if (!/^([a-za-z0-9_.-])+@(([a-za-z0-9-])+\.)+([a-za-z0-9]{2,4})+$/.test(email)) {
            newerrors = { ...newerrors, email: 'email is not valid' };
        }

        seterrors(newerrors);
    }, [name, email, submitted]);

    react.useeffect(() => {
        if (!errors.name && !errors.email) {
            setsubmitted(false);
        }
    }, [errors]);

    return (
        <div>
            <input type="text" value={name} onchange={e => setname(e.target.value)} />

            <input type="email" value={email} onchange={e => setemail(e.target.value)} />
            <button
                mode="contained"
                style={{ borderradius: 0 }}
                contentstyle={{ padding: 10 }}
                uppercase={false}
                onpress={handlesubmit}
            >
                daftar
            </button>

            {submitted && json.stringify(errors)}
        </div>
    );
};

export default untitled;



Related Query

More Query from same tag