简体   繁体   中英

Best way to validate multiple fields in JAVA?

Hi I have many fields that I need to validate for the null and empty ie ""

If I have to validate 5 strings then here is the code.

string.equals("") || string1.equals("") || string2.equals("") || string3.equals("") || string4.equals("")
 || 
string.equals(null) || string1.equals(null) || string2.equals(null) || string3.equals(null) || string4.equals(null)

then it looks odd. If there are about 10 strings then more ugly.

Please tell me the best practice to do it.

You should write a method such as below;;

public static boolean isNullOrEmpty(String... strArr) {
       for (String st : strArr) {
            if  (st==null || st.equals(""))
               return true;

       } 
       return false;
}



boolean result = isNullOrEmpty(string1,strin2,string3,string4,string5);

At least you can optimize:

string1.equals("") || string1.equals(null)

to

StringUtils.isBlank(string1);

StringUtils: http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

Not sure about best practice, but you could tidy up your code:

String[] inputs = new String[5];
inputs[0] = "whatever";

private boolean stringValidate(String[] inputs){
      for(int i=0; i < inputs.size(); i++){
           String currentString = inputs[i];
           if(currentString == null || currentString.equals(""){
               return false; // validation failed
           }
      }
      return true; // Validation passed
}

You could probably use a List make it even nicer.

EDIT

Yes as peter says using VarArgs (which I should do more often!) :

private boolean stringValidate(String... inputs) {
      for (String currentString  : inputs) {
          if(currentString == null || currentString.equals(""){
               return false; // validation failed
           }
      }
      return true; // Validation passed
   }

Called like this:

stringValidate("foo", "bar", "bar");

string.equals(null) would never work, since if string was null, you'd get an NPE. I guess you mean string == null .

Nevertheless, you could use apache commons lang's StringUtils which would reduce the check to StringUtils.isEmpty(string) || ... StringUtils.isEmpty(string) || ...

Create a validate method to handle each one.

private boolean isValid(String parameter){
if (parameter == null || parameter.isEmpty()) return false;
return true;
}

Then you can call this method for each of your strings. Note that if you're using an earlier version of java than 1.6, you can replace the isEmpty() method with !parameter.equals("")

Firstly string.equals(null) is never true. is string is null this will throw a NullPointerException.

You can use string == null || string.equals("") string == null || string.equals("")

The problem you have is that you have many fields/variables which you want to treat in a generic fashion but you have different names. An alternative is to use an array or List

String[] strings = { .... }
boolean notAllSet = false;
for(String s: strings)
   notAllSet |= s==null || s.equals("");

For one thing, a best practice is to do

 "FOO".equals(myString)

instead. This reduces the chance of NPEs and makes it clearer that no mutation is going on. For a discussion of this, see here .

Also, if you really have a collection of strings to compare to, you probably want

 final Set<String> validStrings = ...

 boolean validate(final String foo) {
    return foo!=null && validStrings.contains(foo);
 }

When you're handling a lot of variables of the same type, you can manage them in a structure, such as an ArrayList, then create a method to do the work for you.

public static void main(String[] args){
    ArrayList<String> hold = new ArrayList<String>();
    hold.add(string);
    hold.add(string1);
    hold.add(string2);
    hold.add(string3);
    hold.add(string4);

    if( validate(hold) )
        System.out.println("No blanks, no nulls");
}

public boolean validate(ArrayList<String> hold){
     for( int x = 0; x < hold.size(); x++ ){
          if( hold.get(x).equals("") || hold.get(x).equals(null) )
                return false;
     }

     return true;
}

I know the question is very old, but I find StringUtils to be more suited for this.

StringUtils.isAnyEmpty(String... args)

Or

StringUtils.isAnyBlank(String... args)

Hope this helps someone!

Docs, here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM