Skip to content

Instantly share code, notes, and snippets.

@xyznaveen
Last active October 18, 2018 13:21
Show Gist options
  • Save xyznaveen/79305b82133fe4d1bf2e5f6db6557c4e to your computer and use it in GitHub Desktop.
Save xyznaveen/79305b82133fe4d1bf2e5f6db6557c4e to your computer and use it in GitHub Desktop.
Android EditText and TextInputLayoutValidation snippet.
public class RegisterFragment extends BaseFragment
implements View.OnClickListener {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Simple Implementation Example
List<TextInputLayout> inputLayoutList = new ArrayList<>();
inputLayoutList.add(fullName);
inputLayoutList.add(email);
inputLayoutList.add(password);
inputLayoutList.add(phone);
List<String> errorList = new ArrayList<>();
errorList.add(TextUtil.INP_NAME + TextUtil.ERR_DELIM + "Name format: Firstname Lastname");
errorList.add(TextUtil.INP_EMAIL + TextUtil.ERR_DELIM + "Invalid email address.");
errorList.add(TextUtil.INP_PASS + TextUtil.ERR_DELIM + "Password must be min 6 character.");
errorList.add(TextUtil.INP_PHONE + TextUtil.ERR_DELIM + "Phone number is invalid.");
TextUtil.isInputInvalid(inputLayoutList, errorList);
}
}
public class TextUtil {
public static final String ERR_DELIM = "---";
public static final String INP_EMAIL = "email";
public static final String INP_PASS = "pass";
public static final String INP_PHONE = "phone";
public static final String INP_NAME = "name";
public static final int LEN_PASS = 6;
public static final int LEN_PHONE = 10;
public static final int LEN_RULE_MSG = 2;
/**
* Validates input and displays passed error messages. Making (my own) life easier.
*
* @param inputLayouts input layouts holding user input.
* @param errorMessages error messages to display if the user inputs are invalid
* @param <T> any (not really, only TextInputLayout and EditText)
* @return true even when any one input is invalid, false when every required input are provided
*/
public static <T> boolean isInputInvalid(List<T> inputLayouts, List<String> errorMessages) {
// FALSE because? natural language SEMANTICS
// the method returns true when inputs are invalid
// why am I explaining this here?
boolean isAtLeastOneInvalid = false;
ListIterator<T> iterator = inputLayouts.listIterator();
while (iterator.hasNext()) {
// we need current index for handling error messages
int index = iterator.nextIndex();
// I KNOW, but couldn't figure out any other way to do this
// might actually refactor this? might not! who knows.
String[] ruleAndMessage = errorMessages.get(index).split(ERR_DELIM);
// Only TextInputLayout or EditText
T view = iterator.next();
if (view instanceof TextInputLayout) {
boolean isInputEmpty = true;
TextInputLayout layout = (TextInputLayout) view;
EditText editText = layout.getEditText();
// we do not want a surprise NullPointerException
// also android studio didn't let me continue without this #lol
if (editText != null && editText.getText() != null) {
final String actualInput = editText.getText().toString().trim();
// tricky part ahead, we set true when the input is empty
// if the values are false it means the input is valid from this point onwards
// because isInputEmpty = false(it is not empty(invalid)), makes sense :D
isInputEmpty = actualInput.isEmpty();
// we passed on identifier---error_message
/// 0 --- 1
// hence the length has always have to be true
// 0 is always the rule / identifier
// 1 is always error message
if (ruleAndMessage.length == LEN_RULE_MSG) {
if (ruleAndMessage[0].equalsIgnoreCase(INP_EMAIL)) {
isInputEmpty = !Patterns.EMAIL_ADDRESS.matcher(actualInput).matches();
} else if (ruleAndMessage[0].equalsIgnoreCase(INP_PASS)) {
// password must be at least 6 characters
isInputEmpty = actualInput.length() <= LEN_PASS;
} else if (ruleAndMessage[0].equalsIgnoreCase(INP_PHONE)) {
isInputEmpty = actualInput.length() != LEN_PHONE;
} else if (ruleAndMessage[0].equalsIgnoreCase(INP_NAME)) {
try {
Integer.parseInt(actualInput);
// user enters a numeric name the user might maybe a robot
// from the future ?
isInputEmpty = true;
} catch (NumberFormatException ex) {
// we get an exception because the input is a string
isInputEmpty = actualInput.split(" ").length != 2;
}
}
}
} else if (view instanceof EditText) {
//TODO implement validation for EditText too
}
if (isInputEmpty) {
// the input is invalid show display error message
layout.setErrorEnabled(true);
layout.setError(ruleAndMessage.length == LEN_RULE_MSG
? ruleAndMessage[1]
: ruleAndMessage[0]);
isAtLeastOneInvalid = true;
} else {
// an intelligent one, AWESOME!!!
layout.setError(Constants.STR_EMPTY);
layout.setErrorEnabled(false);
}
}
}
return isAtLeastOneInvalid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment