如何使用自定义验证类型创建自己的editText?

时间:2015-06-15 06:30:52

标签: android validation android-edittext form-fields customizing

我想创建自己的编辑文本字段,该字段用于来自用户的多个条目,具有不同的必需验证集(电子邮件,电话,信用卡,混合字符)。

1 个答案:

答案 0 :(得分:0)

试试这样:

对于CreditCard:

 public boolean isValid(EditText et) {
    try {
      return validateCardNumber(et.getText().toString());
    } catch (Exception e) {
      return false;
    }
  }
 public static boolean validateCardNumber(String cardNumber) throws NumberFormatException {
    int sum = 0, digit, addend = 0;
    boolean doubled = false;
    for (int i = cardNumber.length () - 1; i >= 0; i--) {
      digit = Integer.parseInt (cardNumber.substring (i, i + 1));
      if (doubled) {
        addend = digit * 2;
        if (addend > 9) {
          addend -= 9; 
        }
      } else {
        addend = digit;
      }
      sum += addend;
      doubled = !doubled;
    }
    return (sum % 10) == 0;
  }

对于IpAddress:

public IpAddressValidator(String _customErrorMessage) {
    super(_customErrorMessage, Build.VERSION.SDK_INT>=8?Patterns.IP_ADDRESS:Pattern.compile(
            "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
            + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
            + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
            + "|[1-9][0-9]|[0-9]))"));
}

查看此示例应用程序以获取更多详细信息:here