0

I want to give the validation in all field of form, but my validation is not working perfectly, I also want to give the length for all field except email because it works perfect, other all fields are not getting validate, please help me in this issue.

here is my validation code.

public class Validation {

private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final String PHONE_REGEX = "^[7-9][0-9]{9}$";

// Error Messages
private static final String REQUIRED_MSG = "required";
private static final String EMAIL_MSG = "invalid email";
private static final String PHONE_MSG = "###-#######";

// call this method when you need to check email validation
public static boolean isEmailAddress(EditText editText, boolean required) {
    return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}

// call this method when you need to check phone number validation
public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}

// return true if the input field is valid, based on the parameter passed
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {

    String text = editText.getText().toString().trim();
    // clearing the error, if it was previously set by some other values
    editText.setError(null);

    // text required and editText is blank, so return false
    if ( required && !hasText(editText) ) return false;

    // pattern doesn't match so returning false
    if (required && !Pattern.matches(regex, text)) {
        editText.setError(errMsg);
        return false;
    };

    return true;
}

// check the input field has any text or not
// return true if it contains text otherwise false
public static boolean hasText(EditText editText) {

    String text = editText.getText().toString().trim();
    editText.setError(null);

    // length 0 means there is no text
    if (text.length() == 0) {
        editText.setError(REQUIRED_MSG);
        return false;
    }

    return true;
}
}

please help me in this problem, thank you.

slek
  • 309
  • 6
  • 17
akky777
  • 423
  • 2
  • 6
  • 23

1 Answers1

0

Here is a very good library for validation fields: https://github.com/vekexasia/android-edittext-validator

Tooto
  • 375
  • 2
  • 15