I created a string validator and I need to add these things to check in my input strings. How do I do it?
- Minimum of 6 characters.
- Maximum of 15 characters.
- Digits should not be adjacent to one another like:
- invalid:
bq34
- valid:
b3q4
- invalid:
- Minimum 1 Upper case.
- Minimum 1 lowercase.
- Minimum 2 Numeric Numbers.
- Each character should occur a maximum of once.
- Minimum 1 Special Character.
- Common Allow Character ( $, %, >).
CodePudding user response:
you can check the number of characters of a String using .length(), for 1 upper case letter and 1 lower case letter you should use pattern like this
this is for password validation.
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
Explanation:
(?=.*[A-Z]) // should contain at least one upper case
(?=.*[a-z]) // should contain at least one lower case
(?=.*?[0-9]) // should contain at least one digit
(?=.?[!@#$&~]) // should contain at least one Special character
.{8,} // Must be at least 8 characters in length
@override
String validator(String value) {
if (value.isEmpty) {
return 'Password can\'t be empty';
} else if (value.isNotEmpty) {
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
bool passvalid =
regExp.hasMatch(value);
return passvalid ? null : "Invalid Password";
}
}
CodePudding user response:
Try using this package it has all the validations you are asking for
https://pub.dev/packages/form_field_validator/
This is just an example how to use this package with textfield or textformfield.
final passwordValidator = MultiValidator([
RequiredValidator(errorText: 'password is required'),
MinLengthValidator(8, errorText: 'password must be at least 8 digits long'),
PatternValidator(r'(?=.*?[#?!@$%^&*-])', errorText: 'passwords must have at least one special character')
]);
String password;
Form(
key: _formKey,
child: Column(children: [
TextFormField(
obscureText: true,
onChanged: (val) => password = val,
// assign the the multi validator to the TextFormField validator
validator: passwordValidator,
),
// using the match validator to confirm password
TextFormField(
validator: (val) => MatchValidator(errorText: 'passwords do not match').validateMatch(val, password),
)
]),
);