Home > Blockchain >  specific error of a field in a react form
specific error of a field in a react form

Time:11-19

I am validating if the fields of all the inputs in the form are not empty, for the moment I have done it this way.

const handleSubmit = (e) => {
    if (!formCompra.input1|| !formCompra.input2|| !restForm.input3|| 
    !restForm.input4|| !restForm.input5) {
      alert('you are missing some fields')
    }
}

The code works fine, but the message is very generic, that's why I tried to perform a validation that sends me a message where only the fields are missing, for example "you're missing input1, input2"

CodePudding user response:

With this example, where I assume all of your inputs are controlled, you either need to backlink those values to the element, to know what kind of alert to throw and get some reasonable normal text to throw (you probably don't want to throw "You are missing input5") from data property of HTML element, or in your instance I'd just go and if(){} else if(){} every single case.

The better thing to do would be to get all the inputs from event that you are getting on handleSubmit and check it with those values.

As it's not exactly straight forward to have good responding form in multiple languages there are packages available to solve this. I'd recommend https://www.npmjs.com/package/yup.

Also checking for empty input by doing !value is not the best thing to do.

In case of numeric inputs this can happen !0 = true in case of strings this can !"" = true

CodePudding user response:

Let's say your formComp is an object with values. We should be making a generic error handler here.

let formComp = {
  input1: 'fdsg/',
  input2: 'fdsfsd',
  input3: 321,
  input4: '',
  input5: null
}


let errorMessage = Object.keys(formComp).reduce((message, key) => {
  if (!formComp[key]) {
    message  = `${key} is missing ! \n`
  }
  return message
}, '')

if (errorMessage) console.log(errorMessage)

This is a pretty good use case of reduce method.

CodePudding user response:

You could just loop through formCompra like so:

const data = {
  input1: "1",
  input2: "",
  input3: "3"
}

for (input in data) {
  if (!data[input]) console.log(`you are missing ${input}`)
}

[...]for example "you're missing input1, input2"

If you want to have multiple fields in your error message, you could do something like this:

const data = {
  input1: "1",
  input2: "",
  input3: "3",
  input4: ""
}

const validate = () => {
  let missing_fields = []
  for (input in data) {
    if (!data[input]) missing_fields.push(input)
  }
  let message = "You are missing"
  for (let i = 0; i < missing_fields.length; i  ) {
    if (i === missing_fields.length - 1) {
      message  = ` ${missing_fields[i]}.`
      console.log(message)
    }
    message  = ` ${missing_fields[i]},`
  }
}

validate()


PS: The object keys should be given descriptive names instead of input1 etc. for this approach

  • Related