I think this counts for any other language as well, but I'm using Java for Android in this example here. I'm trying to validate a form, but it has multiple inputs.
if( !anuncio.getEstado().isEmpty() ){
if( !anuncio.getCategoria().isEmpty() ){
if( !anuncio.getTitulo().isEmpty() ){
if( !valor.isEmpty() && !valor.equals("0") ){
if( !anuncio.getTelefone().isEmpty() ){
if( !anuncio.getDescricao().isEmpty() ){
saveForm();
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
Is there any way or method to simplify this? Because let's say if it were 10 inputs, it would be a horrible code doing 10 ifs, you know? How do I simplify this?
CodePudding user response:
In your case this would suffice:
if( !anuncio.getEstado().isEmpty()
&& !anuncio.getCategoria().isEmpty()
&& !anuncio.getTitulo().isEmpty()
&& !valor.isEmpty() && !valor.equals("0")
&& !anuncio.getTelefone().isEmpty()
&& !anuncio.getDescricao().isEmpty() ) {
safeForm();
} else {
showErro("please fill the entire form");
}
For more complex code you may i.e. want to count errors and show messages later if count > 0
etc.
PS also I believe you wanted to write "showError" not "showErro"
CodePudding user response:
More elegant way to write it:
if(!containsEmptyText(anuncio.getEstado(), anuncio.getCategoria(), anuncio.getTitulo(),
valor, anuncio.getTelefone(), anuncio.getDescricao()) && !valor.equals("0") ){
saveForm();
}else
showErro("please fill the entire form");
private static boolean containsEmptyText(String... textArray){
for(String text : textArray)
if(text.isEmpty())
return true;
return false;
}