Flutter正则表达式验证插件regexed_validator的使用

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

Flutter正则表达式验证插件regexed_validator的使用

标题

Flutter正则表达式验证插件regexed_validator的使用

内容

Validating:

  • phone
  • name
  • postalCode
  • email
  • url
  • currency
  • ip
  • date
  • time
  • htmlTags
  • password (strong)
  • password (medium)
  • creditCard

For Dart/Flutter developers. Regexed Validator at pub.dartlang.org

使用

Usage is pretty simple just pass a phone, date, email… to its validation method, see the example below

import 'package:regexed_validator/regexed_validator.dart';

main() {
  print(validator.email('example@example.co.uk')); // true

  print(validator.url('http://www.nowhere.com?product=28&color=blue')); // true

  print(validator.currency('£498.10')); // true

  print(validator.ip('67.52.159.38')); // true

  print(validator.time('114:34 GMT -5'); // true

  print(validator.htmlTags('<strong>Bold</strong>\n'
      '<em>Emphazied</em>\n'
      '<b>Bold</b>\n'
      '<i>Italics</i>\n'
      '<span id="foo" class="bar">Some text</span>\n'
      '<hr />')) // true
}

With Flutter TextField, TextFormField and Forms

There is nothing specific to this package when working with Forms and TextFields, see the example below

TextFormField(
    // The validator receives the text that the user has entered, and use regexed_validator to check if it is a valid string.
    validator: (value) {
      if (!validator.email(value)) {
        return 'Please enter a valid email';
      }
      return null;
    },
),

Here is a complete example, with a Form and an email field:

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    const appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: const MyCustomForm(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({Key? key}) : super(key: key);

  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            // The validator receive the text that the user has entered, and use regexed_validator to check if it is a valid string.
            validator: (value) {
              if (value == null || !validator.email(value)) {
                return ' Please enter a valid email';
              }
              return null;
            },
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 116.0),
            child: ElevatedButton(
              onPressed: () {
                // Validate returns true if the form is valid, or false otherwise.
                if (_formKey.currentState!.validate()) {
                  // If the form is valid, display a snackbar. In the real world,
                  // you'd often call a server or save the information in a database.
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Processing Data')),
                  );
                }
              },
              child: const Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}

示例代码

import 'package:regexed_validator/regexed_validator.dart';

main() {
  print(validator.phone('+1123 - 456-78-90')); // true
  print(validator.name('John Quincy Adams')); // true
  print(validator.postalCode('110101-6543')); // ture
  print(validator.email('example@example.co.uk')); // true
  print(validator.url('http://www.nowhere.com?product=28&color=blue')); // true
  print(validator.currency('£498.10')); // true
  print(validator.ip('67.52.159.38')); // true
  print(validator.date('2000-12-20')); // true
  print(validator.time('14:34 GMT -5')); // true
  print(validator.htmlTags('<strong>Bold</strong>\n'
      '<em>Emphazieded</em>\n'
      '<b>Bold</b>\n'
      '<i>Italics</i>\n'
      '<span id="foo' class="bar">Some text</span>\n'
      '<hr />')); // true
  print(validator.password('sword#42Fish')); // true
  print(validator.creditCard('4000-1234-12234-1234')); // true
}

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

1 回复

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


当然,下面是一个关于如何在Flutter中使用regexed_validator插件来进行正则表达式验证的示例代码。这个插件可以帮助你轻松地在Flutter应用中验证各种输入字段,如电子邮件、电话号码、密码等。

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

dependencies:
  flutter:
    sdk: flutter
  regexed_validator: ^latest_version  # 请替换为实际的最新版本号

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

接下来,你可以在你的Flutter应用中使用RegexedTextFormFieldRegexedValidator来进行正则表达式验证。下面是一个完整的示例代码,展示如何使用RegexedTextFormField来验证电子邮件地址:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Regexed Validator Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Regexed Validator Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: MyForm(),
        ),
      ),
    );
  }
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  final _formKey = GlobalKey<FormState>();
  String _email = '';
  String _errorMessage = '';

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(
              labelText: 'Email',
              errorText: _errorMessage,
            ),
            validator: (value) {
              if (value.isEmpty) {
                return 'Email is required';
              }
              // 使用RegexedTextFormField的话,验证逻辑会在其内部处理,这里仅展示普通TextFormField结合RegexedValidator的用法
              bool isValid = RegexedValidator().regex('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$').validate(value);
              if (!isValid) {
                setState(() {
                  _errorMessage = 'Invalid email address';
                });
                return 'Invalid email address';
              }
              setState(() {
                _errorMessage = '';
              });
              return null;
            },
            onChanged: (value) {
              setState(() {
                _email = value;
              });
            },
          ),
          SizedBox(height: 20),
          RegexedTextFormField(
            decoration: InputDecoration(
              labelText: 'Confirm Email',
            ),
            regex: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
            errorText: 'Invalid email address',
            onChanged: (value) {
              // Handle onChanged if needed
            },
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                // Handle form submission
                print('Email: $_email');
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}

在这个示例中,我们展示了两种使用正则表达式验证输入字段的方法:

  1. 使用TextFormField结合RegexedValidator的静态方法进行验证。
  2. 使用RegexedTextFormField,这是一个封装了正则表达式验证逻辑的TextFormField,使得验证过程更加简洁。

你可以根据你的需求选择合适的方法进行使用。希望这个示例能帮助你更好地理解如何在Flutter中使用regexed_validator插件进行正则表达式验证。

回到顶部