Flutter表单验证插件the_validator的使用

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

Flutter表单验证插件the_validator的使用

the_validator 是一个简单且轻量级的Flutter表单和数据验证包。本文将详细介绍如何使用该插件进行表单验证,并提供完整的示例代码。

如何使用

直接在 TextFormField 中使用

你可以直接在 TextFormFieldvalidator 参数中使用 the_validator

TextFormField(
  controller: _emailController,
  validator: FieldValidator.email(),
  decoration: InputDecoration(labelText: "Email"),
),

独立使用

你也可以将其作为独立的验证器来使用:

bool isValid = Validator.isPassword('SecretPass', shouldContainCapitalLetter: true);

示例用法 (FieldValidator)

以下是如何使用 FieldValidator 来验证电子邮件和密码字段的示例:

TextFormField(
  controller: _emailController,
  validator: FieldValidator.email(),
  decoration: InputDecoration(labelText: "Email"),
),

TextFormField(
  controller: _passwordController,
  validator: FieldValidator.password(
    minLength: 8,
    shouldContainNumber: true,
    shouldContainCapitalLetter: true,
    shouldContainSmallLetter: true,
    shouldContainSpecialChars: true,
    errorMessage: "Password must match the required format",
    isNumberNotPresent: () => "Password must contain number",
    isSpecialCharsNotPresent: () => "Password must contain special characters",
    isCapitalLetterNotPresent: () => "Password must contain capital letters",
  ),
  decoration: InputDecoration(labelText: "Password"),
),

TextFormField(
  controller: _confirmPasswordController,
  obscureText: true,
  validator: FieldValidator.equalTo(_passwordController, message: "Password Mismatch"),
  decoration: InputDecoration(labelText: "Confirm Password"),
),

然后调用 formState.validate() 方法来进行验证:

RaisedButton(
  onPressed: () {
    if (_formKey.currentState.validate()) {
      _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Yay! we got it right!")));
    }
  },
  child: Text("Submit"),
)

示例用法 (Validator)

以下是如何使用 Validator 类来验证密码是否匹配的示例:

var password = 'Secret';
var confirmPassword = 'secret';

if (Validator.isPassword(password, shouldContainCapitalLetter: true)) {
  if (Validator.isEqualTo(password, confirmPassword)) {
    print("Go ahead & grant access");
  } else {
    print("Password mismatch");
  }
}

错误消息

默认情况下,the_validator 会根据指定的验证类型为字段或输入生成合理的错误消息。你也可以覆盖默认的消息。

默认错误消息

例如,FieldValidator.alphaNumeric() 将输出:

  • Field must contain both alphabets and numbers

自定义错误消息

你可以通过传递自定义消息来覆盖默认消息:

FieldValidator.alphaNumeric(message: 'Your username must contain both numbers & alphabets')

完整示例 Demo

以下是包含完整表单验证逻辑的完整示例代码:

import 'package:flutter/material.dart';
import 'package:the_validator/the_validator.dart'; // 引入 the_validator 包

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FormScreen(),
    );
  }
}

class FormScreen extends StatefulWidget {
  [@override](/user/override)
  _FormScreenState createState() => _FormScreenState();
}

class _FormScreenState extends State<FormScreen> {
  final _formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();

  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('Form Validation Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: <Widget>[
              TextFormField(
                controller: _emailController,
                validator: FieldValidator.email(),
                decoration: InputDecoration(labelText: "Email"),
              ),
              SizedBox(height: 20),
              TextFormField(
                controller: _passwordController,
                validator: FieldValidator.password(
                  minLength: 8,
                  shouldContainNumber: true,
                  shouldContainCapitalLetter: true,
                  shouldContainSmallLetter: true,
                  shouldContainSpecialChars: true,
                  errorMessage: "Password must match the required format",
                  isNumberNotPresent: () => "Password must contain number",
                  isSpecialCharsNotPresent: () => "Password must contain special characters",
                  isCapitalLetterNotPresent: () => "Password must contain capital letters",
                ),
                decoration: InputDecoration(labelText: "Password"),
                obscureText: true,
              ),
              SizedBox(height: 20),
              TextFormField(
                controller: _confirmPasswordController,
                validator: FieldValidator.equalTo(_passwordController, message: "Password Mismatch"),
                decoration: InputDecoration(labelText: "Confirm Password"),
                obscureText: true,
              ),
              SizedBox(height: 40),
              RaisedButton(
                onPressed: () {
                  if (_formKey.currentState.validate()) {
                    _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Yay! we got it right!")));
                  }
                },
                child: Text("Submit"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter中使用the_validator插件进行表单验证的详细示例。the_validator是一个流行的Flutter插件,它提供了便捷的表单验证功能。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  the_validator: ^2.0.0  # 确保使用最新版本

2. 导入插件

在你的Dart文件中导入the_validator插件:

import 'package:the_validator/the_validator.dart';

3. 创建一个表单模型

为了使用the_validator进行验证,你需要创建一个表单模型类,并使用@Validatable()注解,然后为每个字段添加相应的验证注解。

import 'package:the_validator/the_validator.dart';

@Validatable()
class SignUpForm {
  @Required(message: "Email is required")
  @Email(message: "Email is not valid")
  String? email;

  @Required(message: "Password is required")
  @MinLength(6, message: "Password must be at least 6 characters")
  String? password;

  @Required(message: "Confirm Password is required")
  @Compare("password", message: "Passwords do not match")
  String? confirmPassword;
}

4. 创建表单UI和验证逻辑

接下来,在你的Flutter组件中创建表单UI,并添加验证逻辑。

import 'package:flutter/material.dart';
import 'package:the_validator/the_validator.dart';
import 'sign_up_form.dart';  // 假设你将表单模型类放在这个文件里

class SignUpScreen extends StatefulWidget {
  @override
  _SignUpScreenState createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State<SignUpScreen> {
  final _formKey = GlobalKey<FormState>();
  late SignUpForm signUpForm;
  late Validator validator;

  @override
  void initState() {
    super.initState();
    signUpForm = SignUpForm();
    validator = Validator(signUpForm);
  }

  void _submit() async {
    if (_formKey.currentState!.validate()) {
      final result = await validator.validate();
      if (result.isEmpty) {
        // 所有字段都有效,提交表单
        print("Form is valid, submit it!");
      } else {
        // 显示错误信息
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text("Please fix the following errors:\n${result.values.join('\n')}"),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sign Up'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Email is required';
                  }
                  return null;
                },
                onSaved: (value) {
                  signUpForm.email = value;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty || value.length < 6) {
                    return 'Password must be at least 6 characters';
                  }
                  return null;
                },
                onSaved: (value) {
                  signUpForm.password = value;
                },
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Confirm Password'),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty || value != signUpForm.password) {
                    return 'Passwords do not match';
                  }
                  return null;
                },
                onSaved: (value) {
                  signUpForm.confirmPassword = value;
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _submit,
                child: Text('Sign Up'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

注意事项

  1. 字段绑定:在TextFormFieldonSaved回调中,你需要手动将用户输入的值赋给表单模型中的相应字段。
  2. 自定义验证逻辑:虽然the_validator提供了丰富的验证注解,但有时候你可能需要自定义验证逻辑,可以在TextFormFieldvalidator回调中处理。
  3. 异步验证:如果需要进行异步验证(例如,检查邮箱是否已被注册),可以在Validator类中进行处理,并在UI中显示结果。

希望这个示例能帮助你理解如何在Flutter中使用the_validator插件进行表单验证。

回到顶部