0

I am making an expense tracker that makes a list of expenses upon submit based of the values in an input. Right now I am wanting to validate if the inputs are empty or not and if they are I want alert the user that they need to fill in the required field. So far I've done this but can't get it to work so far

const addExpenses = () => {



 setExpense(prevState => {
      return [
        ...prevState,
        {
          id: uuidv4(),
          name: expenseName,
          amount: expenseAmount,
          type: expenseType
        }
      ];
    });
    if(expenseName === '') return;
    setExpenseName("");
    setExpenseAmount("");
  };

return (
    <>
      <div className="field">
        <label className="label">Expense name</label>
        <input
          value={expenseName}
          onChange={updateExpenseName}
          type="text"
          className="expense-name"
          placeholder="Expense name"
        />
      </div>
      <div className="field">
        <label className="label">Expense amount</label>
        <input
          value={expenseAmount}
          onChange={updateExpenseAmount}

          type="number"
          className="expense-amount"
          placeholder="Expense amount"
        />
      </div>
3
  • where is the method updateExpenseName? Commented Mar 19, 2020 at 14:58
  • I don't see anything that triggers a submit Commented Mar 19, 2020 at 14:58
  • Read some tutorials and documentation for popular React form validation libraries. Commented Mar 19, 2020 at 15:00

2 Answers 2

1

First things first use some basic HTML validation. like bellow, I use a form and required in my input. By using this you cannot submit the form keeping anything empty

<form onSubmit={handleSubmit}>
  <input
    required
    type="text"
    className="expense-name"
    placeholder="Expense name"
  />

  <button type="submit">Submit</button>
</form>

but still, there are some validation like if use give any space so for that in your handleSubmit add some logic like bellow

const handleSubmit = () =>{
    //as example i am only showing for expenseName
    if(expenseName.trim().length === 0){
        alert('Wrong Input');
    }else{
        //do your job
    }
}

full-example

https://codesandbox.io/embed/dreamy-cherry-qt1qw?fontsize=14&hidenavigation=1&theme=dark

Sign up to request clarification or add additional context in comments.

Comments

0

For detect if input is empty :

if(!(input == null || input == '')) {
 // Continue
}else{
  // Input is empty!
}

This example is not optimised, I know, but it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.