본문 바로가기
My Image
프로그래밍/Android

[Android] 정규표현식을 이용한 Data 검증

by Lim-Ky 2017. 6. 23.
반응형

이번시간에는 오픈시간과 클로징시간을 사용자에게 입력을 받아서


앱이 오픈시간과 클로징시간을 체크해서 시간에 따른 작업을 하는 동작을 어떻게 하는지 알아보자.


우선 실제로 실무에 있으면서 안드로이드 업무를 볼 때 만들었던 소스를 잠시 응용하여 설명하겠다.


우리가 만들어 볼 앱은 대략이렇다.



1. 사용자로부터 오픈시간과 클로징시간을 커스텀 다이얼로그를 통해 입력을 받자.

2. 사용자로부터 입력받은 시간 Data값의 유효성을 정규식표현을 이용해 검증하자.

3. 검증이 된 Data을 시간을 오픈시간,클로징시간 전역변수에 대입한다.

4. 각 시간에 따른 이벤트를 준다. 

(나는 오픈시간과 클로징시간 사이 즉 전시시간을 경우엔 시스템 화면 밝기를 최대로 하고, 아닌시간엔 시스템 화면 밝기를 0으로 준다)




1. 사용자로부터 오픈시간과 클로징시간을 입력 받을 수 있도록 CustomDialog를 만들자.


커스텀다이얼로그를 구성할 레이아웃을 만들자.

res/ 아래에 time_dialog_layout.xml을 만든다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="84dp"
android:text="시간 설정을 ( HH:MM ) 형식으로 입력하세요."
android:gravity="center"
android:textSize="35sp"
android:background="#FFFFBB33"/>

<EditText
android:id="@+id/opening_input"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="시작시간 ex) 08:30" />

<EditText
android:id="@+id/closing_input"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:hint="종료시간 ex) 18:00"/>
</LinearLayout>


그다음 


커스텀다이얼로그에 대한 레이아웃 설정, 

확인/취소 시 처리를 할 리스너 등록,

AlertDialog 생성 및 show();

....등등을 


showTimeConfigDialog() 함수 안에 묶자.



입맛에 따라 showTimeConfigDialog() 함수를 자신이 원하는 위치에서 호출해서 사용하면된다.


기존에 설정된 오픈시간은 08:30 이고, 클로징시간은 19:30 으로 초기화 되어있다.


private static  String CLOSING = "19:30";
private static String OPEN = "08:30";
private void showTimeConfigDialog(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.time_dialog_layout, null);
alertDialog.setView(view);

final EditText open_edit = (EditText) view.findViewById(R.id.opening_input);
final EditText clos_edit = (EditText) view.findViewById(R.id.closing_input);

open_edit.setHint("현재 저장된 시작 시간 : "+OPEN+" ex) 08:30");
clos_edit.setHint("현재 저장된 종료 시간 : "+CLOSING+" ex) 19:30");

/* When positive (yes/ok) is clicked */
alertDialog.setPositiveButton("저장", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
String open = open_edit.getText().toString();
String close = clos_edit.getText().toString();

// Toast.makeText(MainActivity.this, "open_edit"+open+"\nclos_edit"+close, Toast.LENGTH_SHORT).show();

if(checkInvailedTime(open, close)){
Toast.makeText(MainActivity.this, "시간이 설정되었습니다. :)", Toast.LENGTH_SHORT).show();

Toast.makeText(MainActivity.this, "오픈시간 : "+OPEN+"\n종료시간 : "+CLOSING, Toast.LENGTH_LONG).show();

}else{
Toast.makeText(MainActivity.this, "시간을 잘못입력하셨습니다. :(", Toast.LENGTH_SHORT).show();

}
timeConfig_toushSum = 0;
dialog.cancel(); // Your custom code
}
});

/* When negative (No/cancel) button is clicked*/
alertDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "취소했습니다.", Toast.LENGTH_SHORT).show();
timeConfig_toushSum = 0;
// finish(); // Your custom code
dialog.cancel(); // Your custom code
}
});
alertDialog.show();
}


여기서 주목할 점은!!! 사용자로부터 입력받은 Data가 우리가 의도한 시간형식의 Data가 아니면, 따로 예외처리를 해야할 것이다.

나는 개발자라면 한번쯤 들어봤을 정규식표현방법을 이용하여 사용자가 입력한 Data가 내가 의도한 Data에 부합하는지 검증하는 것으로 컨셉을 잡았다.


아래의 사이트를 가면 내가원하는 String을 쓰면 자동으로 언어별로 정규식표현과 검증 로직까지 만들어준다.....

세상 편해졌다.....

아래의 링크를 가서 원하는 String의 정규식과 검증로직을 얻어오자!!

http://www.txt2re.com/index-java.php3?s=14:20&1



이제 거의 다왔다...

검증로직을 나는 조금 커스터마이징해서 아래와 같이checkInvailedTime() 함수로 따로 뺐다.



코드를 보면 알겠지만, 매개변수로 오픈시간과 클로징시간을 받아 오픈시간,클로징시간이 내가 의도한 정규표현식에 부합하면, 

검증된 Data이기 때문에 처음 초기화 해논 시간에 대입을 시킨다.


또 입력받은 클로징시간과 오픈시간이 둘 다 유효하지않은 값들이면, 

false를 리턴해 checkInvailedTime()함수를 호출한 곳에 예외처리를 줄 수 있고 

하나라도 유효한 값이면 해당 매칭 로직을 처리하고 return을 하도록 로직을 짰다.



2. 사용자로부터 입력받은 시간 Data값의 유효성을 정규식표현을 이용해 검증하자.


private Boolean checkInvailedTime(String open, String close){

Boolean vaildOpenFlag = false;
Boolean vaildClosFlag = false;

String re1="((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)"; // HourMinuteSec 1

Pattern p = Pattern.compile(re1,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher openMatch = p.matcher(open);
Matcher closeMatch = p.matcher(close);
if (openMatch.find())
{
OPEN = open;
vaildOpenFlag = true;
}
if (closeMatch.find())
{
CLOSING = close;
vaildClosFlag = true;
}

if(vaildOpenFlag || vaildClosFlag){

return true;
}

return false;

}


 

정리하자면 사용자에게 Data를 입력받기 위해 Dialog를 만들었고, 


Dialog를 통해 Data를 받아 정규표현식을 거쳐 내가 원하는 Data인지 검증을 하고,


검증이 된 Data이면, Data를 사용하면 된다.  오늘은 여기까지 그만 시마이..





반응형

댓글