first last
first last

Reputation: 15

making fields validation at the same time

I have 3 fields (name, password, email). I want to check if they are valid or not. I wrote the following

 public boolean isValidInput() {
     if(name.isValid()){
         return false;
       }
      if(password.isInValid()){
         return false;
       }
       if(email.isInValid()){
         return false;
       }
      return true;
  }

so this will give me a single invalid. But what to do if I want to show the invalids all at the same time?

Upvotes: 0

Views: 54

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

You could simply return an integer from the function like this

 public int isValidInput() {
     if(name.isValid()){
         return 1;
       }
      if(password.isInValid()){
         return 2;
       }
       if(email.isInValid()){
         return 3;
       }
      return 0;
  }

and then check the integer to find out which one failed!

It would be better of course to define static final ints with the names of the errors to make the code more readable and robust.

Upvotes: 0

Kishore Bandi
Kishore Bandi

Reputation: 5711

There are multiple ways you can handle this. But each of them need a change in the caller to handle these cases.

  1. Create a custom exception which accepts a list of messages. Every time a validation failed add the error to the list, at the end of isValidInput() if the list is not empty then throw an exception with the list of errors.
  2. Return the list of errors from above, instead of throwing exception.
  3. Return a list of boolean variable and each index in the list will represent the status of a validation (name, email, etc)
  4. Have an Enum of all fields that are present. Return a list of enum that failed. Empty list indicates that no error has occurred.

There are still a lot of other ways to handle this. It all depends on what suits you the best.
I would say, try some of them and see how it goes.

Upvotes: 1

Related Questions