验证表单中的编辑文本

时间:2014-03-05 06:15:28

标签: android validation

我想在表单的所有字段中进行验证,但我的验证工作不完美,我还想为除了电子邮件之外的所有字段提供长度,因为它工作正常,其他所有字段都没有得到验证,请帮助我在这个问题上。

这是我的验证码。

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

请帮助我解决这个问题, 谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个非常好的验证字段库:https://github.com/vekexasia/android-edittext-validator