/app/src/main/java/com/eventyay/organizer/utils/ValidateUtils.java

https://github.com/fossasia/open-event-orga-app · Java · 63 lines · 48 code · 13 blank · 2 comment · 3 complexity · 0d695270427e3359a60239a42bf3999c MD5 · raw file

  1. package com.eventyay.organizer.utils;
  2. import android.text.Editable;
  3. import android.text.TextUtils;
  4. import android.text.TextWatcher;
  5. import com.eventyay.organizer.common.Function;
  6. import com.google.android.material.textfield.TextInputLayout;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9. public final class ValidateUtils {
  10. private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
  11. Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
  12. private static final Pattern VALID_URL_REGEX =
  13. Pattern.compile("^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
  14. private ValidateUtils() {
  15. }
  16. public static boolean validateEmail(String emailStr) {
  17. Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
  18. return matcher.find();
  19. }
  20. public static boolean validateUrl(String urlStr) {
  21. Matcher matcher = VALID_URL_REGEX.matcher(urlStr);
  22. return matcher.find();
  23. }
  24. public static void validate(TextInputLayout textInputLayout, Function<String, Boolean> validationReference, String errorResponse) {
  25. textInputLayout.getEditText().addTextChangedListener(new TextWatcher() {
  26. @Override
  27. public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  28. // Nothing here
  29. }
  30. @Override
  31. public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  32. if (validationReference.apply(charSequence.toString())) {
  33. textInputLayout.setError(null);
  34. textInputLayout.setErrorEnabled(false);
  35. } else {
  36. textInputLayout.setErrorEnabled(true);
  37. textInputLayout.setError(errorResponse);
  38. }
  39. if (TextUtils.isEmpty(charSequence)) {
  40. textInputLayout.setError(null);
  41. textInputLayout.setErrorEnabled(false);
  42. }
  43. }
  44. @Override
  45. public void afterTextChanged(Editable editable) {
  46. // Nothing here
  47. }
  48. });
  49. }
  50. }