在 JAVA 中验证多个字段的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5513790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:29:54  来源:igfitidea点击:

Best way to validate multiple fields in JAVA?

javavalidation

提问by Muhammad Imran Tariq

Hi I have many fields that I need to validate for the nulland empty i.e ""

嗨,我有很多字段需要验证空值和空,即“”

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

如果我必须验证 5 个字符串,那么这里是代码。

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.

那么它看起来很奇怪。如果有大约 10 个字符串,则更难看。

Please tell me the best practice to do it.

请告诉我这样做的最佳实践。

回答by Gursel Koca

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);

回答by James.Xu

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

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

回答by Blundell

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.

您可能可以使用 List 使其更好。

EDIT

编辑

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

是的,正如 peter 所说的使用 VarArgs (我应该更频繁地这样做!)

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");

回答by Peter Lawrey

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

首先 string.equals(null) 永远不是真的。is string is null 这将抛出一个 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("");

回答by Thomas

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

string.equals(null)永远不会工作,因为如果字符串为空,你会得到一个 NPE。我猜你的意思是string == null

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

不过,您可以使用 apache commons lang'sStringUtils将检查减少到StringUtils.isEmpty(string) || ...

回答by Riggy

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("")

然后您可以为每个字符串调用此方法。请注意,如果您使用的 Java 版本低于 1.6,则可以将该isEmpty()方法替换为!parameter.equals("")

回答by Mohamed Anees A

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

我知道这个问题很老,但我发现StringUtils更适合这个。

StringUtils.isAnyEmpty(String... args)

StringUtils.isAnyEmpty(String... args)

Or

或者

StringUtils.isAnyBlank(String... args)

StringUtils.isAnyBlank(String... args)

Hope this helps someone!

希望这对某人有帮助!

Docs, here

文档,在这里

回答by andersoj

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.

反而。这减少了 NPE 的机会,并使没有发生突变的情况更加清楚。有关此问题的讨论,请参见此处

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);
 }

回答by Black Box Operations

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.

当您处理大量相同类型的变量时,您可以在一个结构中管理它们,例如 ArrayList,然后创建一个方法来为您完成工作。

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;
}