입력 검증 기법
검증기, 정규 표현식 및 사용자 지정 로직을 사용해 양식 필드의 클라이언트 측 검증을 구현하고 데이터 무결성을 보장합니다.
입력 검증 기법은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Flutter Mobile Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What is Input Validation?
When users enter data into your app, you need to make sure it's correct and safe. This process is called input validation.
It's crucial for maintaining data quality and preventing errors or security issues, ensuring your application works as expected.
Why Validate User Input?
Validation helps in many ways to create robust and user-friendly applications:
- Data Integrity: Ensures data fits expected formats (e.g., email looks like an email).
- User Experience: Guides users to enter correct information, reducing frustration.
- Security: Prevents malicious input that could exploit your app (e.g., SQL injection).
- Business Logic: Ensures data meets specific business rules (e.g., age requirements, unique usernames).
The TextFormField Validator
In Flutter, the TextFormField widget has a special property called validator. This property takes a function that checks the input value.
If the input is invalid, the function should return an error message (a String). If it's valid, it should return null.
Basic Empty Field Check
Let's see a simple validator that checks if a text field is empty. If it is, an error message appears below the field.
Try typing something, then deleting it and submitting to see the error.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Validation Demo',
home: Scaffold(
appBar: AppBar(title: const Text('Basic Validation')),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: const InputDecoration(
hintText: 'Enter your name',
labelText: 'Name',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Processing Data')),
);
}
},
child: const Text('Submit'),
),
),
],
),
);
}
}
Displaying Validation Errors
When a validator function returns a String (an error message), the TextFormField automatically displays this message below the input field in a distinct red color.
This immediate visual feedback helps users understand what went wrong and how to fix it, improving the overall user experience.
Custom Logic: Password Check
You can write any custom logic inside your validator function. Here, we check if a password is at least 6 characters long, which is a common security practice.
This demonstrates how to implement rules beyond simple empty checks.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Validation Demo',
home: Scaffold(
appBar: AppBar(title: const Text('Custom Validation')),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
obscureText: true,
decoration: const InputDecoration(
hintText: 'Enter a password',
labelText: 'Password',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
if (value.length < 6) {
return 'Password must be at least 6 chars';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Password is valid!')),
);
}
},
child: const Text('Submit'),
),
),
],
),
);
}
}
Regular Expressions (Regex)
For more complex validation patterns, like checking email formats, phone numbers, or specific alphanumeric sequences, Regular Expressions (Regex) are incredibly powerful.
A regex is a sequence of characters that defines a search pattern. Dart's RegExp class lets you use them easily.
Email Validation with Regex
Here's how to use a simple regular expression to validate an email address format. It checks for a basic pattern: text@text.domain.
Remember, comprehensive email validation can be complex, but this regex provides a good starting point for common formats.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Regex Validation Demo',
home: Scaffold(
appBar: AppBar(title: const Text('Email Validation')),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
final RegExp emailRegex = RegExp(
r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+"
);
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: 'Enter your email',
labelText: 'Email',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter an email';
}
if (!emailRegex.hasMatch(value)) {
return 'Please enter a valid email format';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Email is valid!')),
);
}
},
child: const Text('Submit'),
),
),
],
),
);
}
}
Triggering Validation Manually
Validation is typically triggered when the user tries to submit the form. You do this by calling _formKey.currentState!.validate() inside an onPressed handler for a button.
This method runs all validators in the Form and returns true if all are valid, false otherwise. You can also use autovalidateMode on the Form widget to validate inputs as they change, as shown in the example.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Auto Validate Demo',
home: Scaffold(
appBar: AppBar(title: const Text('Auto-Validation')),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
// Auto-validate as user types
autovalidateMode: AutovalidateMode.always,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: const InputDecoration(
hintText: 'Enter text (min 3 chars)',
labelText: 'Input',
),
validator: (value) {
if (value == null || value.length < 3) {
return 'Must be at least 3 characters';
}
return null;
},
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
// Manual validation still works
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Input is valid!')),
);
}
},
child: const Text('Submit'),
),
),
],
),
);
}
}
Validation Check
Which of the following are valid ways to implement input validation in Flutter?
Recap: Input Validation
In this lesson, you learned about client-side input validation in Flutter.
- We covered why validation is essential for data integrity, user experience, and security.
- You used the
validatorproperty ofTextFormFieldto define validation rules. - We explored implementing custom logic and using
RegExpfor complex patterns. - Finally, you saw how to trigger validation using
_formKey.currentState!.validate()andautovalidateMode.
Well done! You're now equipped to build more robust and user-friendly forms.
자주 묻는 질문
“입력 검증 기법” 강의는 무료인가요?
네 — “입력 검증 기법” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“입력 검증 기법”에서 뭘 배우나요?
검증기, 정규 표현식 및 사용자 지정 로직을 사용해 양식 필드의 클라이언트 측 검증을 구현하고 데이터 무결성을 보장합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“입력 검증 기법” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.