我已经创建了一个用于验证PAN卡详细信息的代码,除了在Android 5.0.2上运行的ASUS设备外,它在每个设备上都能正常工作。那部手机只接受一个字母,剩下9位数字。
以下是我在MainActivity中的代码:
private EditText txt;
txt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
txt.removeTextChangedListener(this);
String mDetails=txt.getText().toString().toUpperCase();
txt.setText(mDetails.replaceAll("[^a-zA-Z0-9]", ""));
txt.setSelection(txt.getText().toString().length());
txt.addTextChangedListener(this);
if(s.length()==10)
{
if(!isValidPancard(s.toString()))
{
txt.setError("Invalid pan card");
}
else
Toast.makeText(MainActivity.this,"Valid",Toast.LENGTH_LONG).show();
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
验证逻辑:
public static boolean isValidPancard(String pancardNo) {
String PAN_PATTERN = "[A-Z]{3}[P]{1}[A-Z]{1}[0-9]{4}[A-Z]{1}";
Pattern pattern = Pattern.compile(PAN_PATTERN);
Matcher matcher = pattern.matcher(pancardNo);
return matcher.matches();
}