I am trying to make a validation for URL which is accept only ‘https’ and reject ‘http’. I am using form_field_validator for it and I probably understand how to use it. However, I have no idea how to write the regex. Could anyone help me to solve this? This is the code down below.
url_validator.dart
import 'package:form_field_validator/form_field_validator.dart';
class UrlValidator extends TextFieldValidator {
UrlValidator({required String errorText}) : super(errorText);
// I would like to validate only 'https' but this code doesn't work
var urlPattern =
r'https';
@override
bool isValid(String? value) => RegExp(urlPattern).hasMatch(value!);
}
validators.dart
import 'package:form_field_validator/form_field_validator.dart';
final urlValidator = MultiValidator([
UrlValidator(errorText: 'URL is invalid'),
]);
2
Answers
Try this regex hope this will work.
You can use a regular expression to validate URLs in Flutter using the form_field_validator package. To accept only "https" URLs and reject "http" URLs, you can use the following regular expression pattern and a RegExp validator:
RegExp regex = RegExp(r'^https://[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$');