본문 바로가기
개발/안드로이드

EditText Filter (한글, 영어, 숫자만 입력, 특수문자 체크)

by darksilber 2019. 2. 20.
반응형

출처 - http://blog.naver.com/PostView.nhn?blogId=thesims1004&logNo=50182572762

 

// 영문만 허용
protected InputFilter filterAlpha = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Pattern ps = Pattern.compile("^[a-zA-Z]+$");

if (!ps.matcher(source).matches()) {
return "";
return null;
}; 

// 영문만 허용 (숫자 포함)
protected InputFilter filterAlphaNum = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Pattern ps = Pattern.compile("^[a-zA-Z0-9]+$");

if (!ps.matcher(source).matches()) {
return "";
return null;
}; 

// 한글만 허용
public InputFilter filterKor = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Pattern ps = Pattern.compile("^[ㄱ-ㅎ가-힣]+$");

if (!ps.matcher(source).matches()) {
return "";
return null;
}; 


//한글, 숫자, 영어 허용
protected InputFilter filterKoEnNum = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Pattern ps = Pattern.compile("^[a-zA-Z0-9ㄱ-ㅎ가-힣]+$");

if (!ps.matcher(source).matches()) {
return "";
return null;
}; 

//한글, 숫자, 영어소문자, 띄어쓰기 허용
protected InputFilter filterKoEnNum2 = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if(source.equals("")){ // for backspace
    return source;
  }
  if(source.toString().matches("[a-z0-9ㄱ-ㅎ가-힣 ]+")){
    return source;
  }
  Log.e("TAG", "특수문자 및 영문대문자는 입력하실 수 없습니다.");
  return "";
}; 

//파일명에서 특수문자 사용 체크 
특수문자 체크 함수(validateFileName) : http://blog.naver.com/thesims1004/50187197892
InputFilter specialCharacterInFileNameFilter = new InputFilter() { 
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 
boolean isOK = false;
String sText = new StringBuilder(source).toString();
try{
isOK = validateFileName(sText);
}
catch (Exception e) {
}

if (!isOK) {    
Toast t = Toast.makeText(getBaseContext(), "Please try without special characters.", Toast.LENGTH_SHORT);
t.show();
return "";   
}    
return source;
}
};

// 필터 적용
mEditText.setFilters(new InputFilter[] { filterKoEnNum });

 

반응형

댓글