flutter textfield 身份证正则
时间: 2023-10-19 07:09:02 浏览: 53
在Flutter中,可以使用正则表达式对TextField输入的内容进行验证。如果你要验证身份证号码,可以使用以下正则表达式:
```
RegExp(r'^[1-9]\d{5}(18|19|2[0-9])\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}(\d|X|x)$')
```
这个正则表达式可以匹配18位或者15位的身份证号码。你可以在TextField的输入监听回调中使用这个正则表达式进行验证。以下是一个示例:
```dart
TextField(
onChanged: (value) {
RegExp regExp = RegExp(r'^[1-9]\d{5}(18|19|2[0-9])\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}(\d|X|x)$');
if (regExp.hasMatch(value)) {
// 输入的值是有效的身份证号码
} else {
// 输入的值不是有效的身份证号码
}
},
)
```
相关问题
Flutter TextField 手机号正则表达式输入框
好的,关于 Flutter TextField 手机号正则表达式输入框,可以这样实现:
```dart
TextField(
decoration: InputDecoration(
labelText: '手机号',
hintText: '请输入手机号',
),
keyboardType: TextInputType.phone,
inputFormatters: [
WhitelistingTextInputFormatter(RegExp("[0-9]")), // 只允许输入数字
LengthLimitingTextInputFormatter(11), // 限制长度为11位
PhoneTextInputFormatter(), // 格式化手机号
],
)
```
其中 `PhoneTextInputFormatter` 是自定义的一个手机号格式化器,实现如下:
```dart
class PhoneTextInputFormatter extends TextInputFormatter {
// 自定义手机号格式化正则表达式
final _regexp = RegExp(r'^(\d{3})(\d{1,4})?(\d{1,4})?$');
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
// 获取输入的文本
String text = newValue.text;
// 如果输入为空或格式已经正确,则不做处理
if (text.isEmpty || _regexp.hasMatch(text)) {
return newValue;
}
// 格式化手机号
String formattedText = '';
for (int i = 0; i < text.length; i++) {
formattedText += text[i];
if (i == 2 || i == 6) {
formattedText += ' ';
}
}
// 返回格式化后的文本和光标位置
return TextEditingValue(
text: formattedText,
selection: TextSelection.collapsed(offset: formattedText.length),
);
}
}
```
这样就实现了一个可以输入手机号的 TextField,并且会自动格式化手机号的输入框。
flutter 特殊符号正则表达式
Flutter 中,可以使用正则表达式来匹配特殊符号。以下是一些常见的特殊符号的正则表达式:
1. 匹配邮箱地址:
```
RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$')
```
2. 匹配 URL 地址:
```
RegExp(r'^https?:\/\/[^\s]+')
```
3. 匹配手机号码:
```
RegExp(r'^1\d{10}$')
```
4. 匹配身份证号码:
```
RegExp(r'^\d{17}[\dXx]$')
```
5. 匹配中文字符:
```
RegExp(r'[\u4e00-\u9fa5]')
```
6. 匹配空白字符:
```
RegExp(r'\s+')
```
7. 匹配特殊符号:
```
RegExp(r'[^\u4e00-\u9fa5\w\s]+')
```
以上是一些常见的特殊符号的正则表达式,你可以根据自己的需求来选择使用哪些。