user 1017
user 1017

Reputation: 11

input form validation by array field

i have 2 text field in reactjs forms.i have validate this input field if it has empty strings and undefined value and shown in toast message.i got problem in validating individual input field value lets say, want to validate the name field value should should gets greater than 5 characters and emailfield with regex

PERSON form

 const validate_data = (fieldValues = values) => {

   let check_fields = [

            {
                name: "Name",
                msg:"please enter Name"

                 //value:"greater than 5 characters"

            },
            {
                name: "Email",
                msg:"please enter Email address"
            },
          
     
        ]
        for(let checks in check_fields){
         
            let _checks = check_fields[checks]
            if (fieldValues[_checks["name"]] === "" || undefined ) {
                toast.error(_checks["msg"])
                return false
            }         
        }
return true 
}

const {values,handleInputChange} = useForm(data,true,validate_data);

**input form
              name="name"
                label="productname"
                    value={values.name }
                        onChange={handleInputChange} 
                       
                    />

**useformcomponent**

export function useForm(initialFValues,validateOnChange = false, validate) 
{
const handleInputChange = e => 
{
    const { name, value } = e.target
    setValues({
        ...values,
        [name]: value
    })
    if (validateOnChange)
        validate({ [name]: value })
}

Upvotes: 0

Views: 561

Answers (1)

HoldOffHunger
HoldOffHunger

Reputation: 20951

If you want to make sure it requires at least 5 characters, update your config to have a minlength:5 property...

{
    name: "Name",
    msg:"please enter Name",
    minlength: 5
},

And then update your validation to use the new config, by checking if a minlength is defined and then comparing the length(input) against this, with our condition being (_checks['minlength'] && length(fieldValues[_checks["name"]]) < _checks['minlength'])...

if (
    fieldValues[_checks["name"]] === "" ||
    fieldValues[_checks["name"]] === undefined ||
    (_checks['minlength'] && length(fieldValues[_checks["name"]]) < _checks['minlength'])) {
    toast.error(_checks["msg"]);
    return false;
}

Addendum: I fixed this... if (fieldValues[_checks["name"]] === "" || undefined ) { to .... if (fieldValues[_checks["name"]] === "" || fieldValues[_checks["name"]] === undefined ) {. I think this was a typo.

Upvotes: 0

Related Questions