Flutter表单验证插件simple_form_validations的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter表单验证插件simple_form_validations的使用

Simple Validations 是一个Dart包,它提供了一组用于常见数据验证场景的验证器。它可以简化在表单中验证用户输入的过程,确保用户输入的数据符合特定的标准。

使用

要使用此插件,请在 pubspec.yaml 文件中添加 simple_form_validations 作为依赖项。

示例

import 'package:flutter/material.dart';
import 'package:simple_form_validations/simple_form_validations.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Validation Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    final formKey = GlobalKey<FormState>();

    return Scaffold(
      body: SafeArea(
        child: Container(
          padding: const EdgeInsetsDirectional.all(22),
          child: Form(
            key: formKey,
            child: Column(
              children: [
                TextFormField(
                  validator: (value) => SimpleValidations.usernameOrEmailValidator(value),
                  decoration: const InputDecoration(
                    hintText: 'Validator Demo',
                    enabledBorder: OutlineInputBorder(),
                    focusedBorder: OutlineInputBorder(),
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 22),
                TextFormField(
                  validator: (value) => SimpleValidations.passwordValidator(value),
                  decoration: const InputDecoration(
                    hintText: 'Strong Password Validator Demo',
                    enabledBorder: OutlineInputBorder(),
                    focusedBorder: OutlineInputBorder(),
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 22),
                ElevatedButton(
                  onPressed: () {
                    if (formKey.currentState!.validate()) {
                      print("Valid data!");
                    }
                  },
                  child: const Text('提交'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter表单验证插件simple_form_validations的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter表单验证插件simple_form_validations的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用simple_form_validations插件来进行表单验证的代码示例。这个插件提供了方便的方法来验证各种表单输入,如文本字段、电子邮件、密码等。

首先,你需要在你的pubspec.yaml文件中添加simple_form_validations依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_form_validations: ^3.0.0  # 请使用最新版本号

然后运行flutter pub get来安装依赖。

接下来是一个简单的Flutter应用示例,展示了如何使用simple_form_validations进行表单验证:

import 'package:flutter/material.dart';
import 'package:simple_form_validations/simple_form_validations.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Form Validation Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyFormPage(),
    );
  }
}

class MyFormPage extends StatefulWidget {
  @override
  _MyFormPageState createState() => _MyFormPageState();
}

class _MyFormPageState extends State<MyFormPage> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _emailController;
  late TextEditingController _passwordController;
  late TextEditingController _confirmPasswordController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _emailController = TextEditingController();
    _passwordController = TextEditingController();
    _confirmPasswordController = TextEditingController();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      // 在这里处理表单提交,例如发送到服务器
      print('Form submitted successfully!');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Validation Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: 'Name'),
                validator: MultiValidator([
                  RequiredValidator(errorText: 'Name is required'),
                  MinLengthValidator(5, errorText: 'Name must be at least 5 characters long'),
                ]),
              ),
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
                validator: MultiValidator([
                  RequiredValidator(errorText: 'Email is required'),
                  EmailValidator(errorText: 'Invalid email address'),
                ]),
              ),
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: MultiValidator([
                  RequiredValidator(errorText: 'Password is required'),
                  MinLengthValidator(8, errorText: 'Password must be at least 8 characters long'),
                ]),
              ),
              TextFormField(
                controller: _confirmPasswordController,
                decoration: InputDecoration(labelText: 'Confirm Password'),
                obscureText: true,
                validator: (value) {
                  if (value != _passwordController.text) {
                    return 'Passwords do not match';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的表单,包括名称、电子邮件、密码和确认密码字段。每个字段都使用了TextFormField,并且为每个字段添加了验证器。RequiredValidator用于确保字段不为空,MinLengthValidator用于检查最小长度,EmailValidator用于验证电子邮件格式。

注意,对于密码确认字段,我们自定义了一个简单的验证器来检查两次输入的密码是否一致。

运行这个应用,你会看到一个带有验证功能的表单。当表单字段不满足验证条件时,点击提交按钮会显示相应的错误信息。

回到顶部