0Pricing
Flutter Mobile Development · บทเรียน

เทคนิคการตรวจสอบข้อมูลนำเข้า

พัฒนาการตรวจสอบข้อมูลฝั่งไคลเอ็นต์สำหรับช่องในแบบฟอร์ม โดยใช้ตัวตรวจสอบ นิพจน์ทั่วไป และตรรกะแบบกำหนดเอง เพื่อรับประกันความถูกต้องของข้อมูล

เทคนิคการตรวจสอบข้อมูลนำเข้า เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 validator property of TextFormField to define validation rules.
  • We explored implementing custom logic and using RegExp for complex patterns.
  • Finally, you saw how to trigger validation using _formKey.currentState!.validate() and autovalidateMode.

Well done! You're now equipped to build more robust and user-friendly forms.

คำถามที่พบบ่อย

บทเรียน “เทคนิคการตรวจสอบข้อมูลนำเข้า” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เทคนิคการตรวจสอบข้อมูลนำเข้า” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เทคนิคการตรวจสอบข้อมูลนำเข้า”

พัฒนาการตรวจสอบข้อมูลฝั่งไคลเอ็นต์สำหรับช่องในแบบฟอร์ม โดยใช้ตัวตรวจสอบ นิพจน์ทั่วไป และตรรกะแบบกำหนดเอง เพื่อรับประกันความถูกต้องของข้อมูล คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “เทคนิคการตรวจสอบข้อมูลนำเข้า” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม

ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. วิดเจ็ต Form และตัวควบคุม
  2. เทคนิคการตรวจสอบข้อมูลนำเข้า
  3. ช่องแบบฟอร์มแบบกำหนดเอง
  4. โฟกัส แป้นพิมพ์ และประสบการณ์ผู้ใช้ด้านการป้อนข้อมูล
← กลับไปที่ Flutter Mobile Development