본문 바로가기

소프트웨어 /Flutter

[Flutter] TextFormField를 이용하여 회원가입 시(이메일, 비밀번호) 형식 유효성(정규식) 검사하기

반응형

임의의 어느 사이트에서 회원가입을 할 때 이메일과 비밀번호를 입력합니다.

이메일과 비밀번호의 경우 패턴 검사를 하는데요.

정규식 패턴에 맞지 않은 경우 형식에 맞춰 다시 입력을 해야 합니다.

아래와 같이 잘못된 이메일과 비밀번호를 입력했을 때 에러메세지를 띄워주는 코드를 작성해봅시다.

정규식 패턴을 가지고 이메일과 비밀번호를 체크하는 방법을 알아봅시다.

형식에 맞지 않은 이메일과 비밀번호를 입력했을 때
형식에 맞는 이메일과 비밀번호를 입력했을 때

 

 

 

 

 

먼저 flutter 프로젝트를 하나 생성해줍니다. (프로젝트 생성과정은 생략합니다.)

 

validate.dart 파일을 만들어 이메일과 비밀번호 유효성 검사를 하기위해 정규식을 이용하여 String으로 리턴받을 수 있는 메소드를 만들어줍니다.

 

class CheckValidate{
  String validateEmail(FocusNode focusNode, String value){
    if(value.isEmpty){
      focusNode.requestFocus();
      return '이메일을 입력하세요.';
    }else {
      Pattern pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
      RegExp regExp = new RegExp(pattern);
      if(!regExp.hasMatch(value)){
        focusNode.requestFocus();	//포커스를 해당 textformfield에 맞춘다.
        return '잘못된 이메일 형식입니다.';
      }else{
        return null;
      }
    }
  }

  String validatePassword(FocusNode focusNode, String value){
    if(value.isEmpty){
      focusNode.requestFocus();
      return '비밀번호를 입력하세요.';
    }else {
      Pattern pattern = r'^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?~^<>,.&+=])[A-Za-z\d$@$!%*#?~^<>,.&+=]{8,15}$';
      RegExp regExp = new RegExp(pattern);
      if(!regExp.hasMatch(value)){
        focusNode.requestFocus();
        return '특수문자, 대소문자, 숫자 포함 8자 이상 15자 이내로 입력하세요.';
      }else{
        return null;
      }
    }
  }

}

 

다음으로 SignUp.dart 이름의 dart파일을 하나 만들어 이메일과 비밀번호 입력창과 확인버튼을 만들어줍니다.

 

stful을 이용해서 클래스를 만들어 줍니다.

 

class SignUp extends StatefulWidget {
  const SignUp({Key key}) : super(key: key);

  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

 

이제 위젯을 달아주는데 TextFormField를 사용합니다.

TextFormField란?

일반적으로 사용하는 TextField 에 validator 기능이 추가된 것으로 유효성 검증을하여 에러메세지를 사용자에게 보여줄 수 있습니다. 주로 회원가입을 하는데 사용됩니다.

TextFormField 검증을 사용하기 위해선 build의 body를 Form으로 감싸줘야 합니다. 그리고 GlobalKey를 사용해야 합니다.

 

class SignUp extends StatefulWidget {
  const SignUp({Key key}) : super(key: key);

  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  FocusNode _emailFocus = new FocusNode();
  FocusNode _passwordFocus = new FocusNode();

  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Validate Test')),
      body: new Form(
          key: formKey,
          child: Column(
          children: [
          _showEmailInput(),
          _showPasswordInput(),
            _showOkBtn()
        ],)
      ),
    );
  }

  Widget _showEmailInput(){
    return Padding(padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
    child: Column(
      children: [
        Padding(padding: EdgeInsets.fromLTRB(20, 20, 20, 0),
          child: TextFormField(
            keyboardType: TextInputType.emailAddress,
            focusNode: _emailFocus,
            decoration: _textFormDecoration('이메일', '이메일을 입력해주세요'),
            validator: (value) => CheckValidate().validateEmail(_emailFocus, value),
          )),
      ],
    ));
  }

  Widget _showPasswordInput(){
    return Padding(padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
        child: Column(
          children: [
            Padding(padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                child: TextFormField(
                    focusNode: _passwordFocus,
                    keyboardType: TextInputType.visiblePassword,
                    obscureText: true,
                    decoration: _textFormDecoration('비밀번호', '특수문자, 대소문자, 숫자 포함 8자 이상 15자 이내로 입력하세요.'),
                    validator: (value) => CheckValidate().validatePassword(_passwordFocus, value),
                )),
          ],
        ));
  }

  InputDecoration _textFormDecoration(hintText, helperText){
    return new InputDecoration(
      contentPadding: EdgeInsets.fromLTRB(0, 16, 0, 0),
      hintText: hintText,
      helperText: helperText,
    );
  }

  Widget _showOkBtn(){
    return Padding(padding: EdgeInsets.only(top: 20),
      child: MaterialButton(
        height: 50,
        child: Text('확인'),
        onPressed: (){
          formKey.currentState.validate();
        },
      ));
  }
}

 

validator를 이용해 CheckValidate 클래스 안에 있는 이메일, 비밀번호 유효성 검사를 통해 String 형식으로 리턴을 받아 그 값을 TextFormField에 나타내줍니다.