validate: Add UriField
This commit is contained in:
parent
30d169b4ee
commit
d233b1c37e
4 changed files with 38 additions and 1 deletions
|
@ -1,5 +1,5 @@
|
|||
# 3.0.0-alpha.1
|
||||
* Add `MapField`.
|
||||
* Add `MapField` and `UriField`.
|
||||
|
||||
# 3.0.0-alpha
|
||||
* Rewrite, based on `Field` and `Form`, rather than strings.
|
||||
|
|
|
@ -52,6 +52,7 @@ There are several included field types:
|
|||
* `FileField` - Validates a file in `req.uploadedFiles`.
|
||||
* `ImageField` - Uses `package:image` to decode an `UploadedFile` into an image.
|
||||
* `MapField` - Validates a Map using a Form.
|
||||
* `UriField` - Parses text input into a `Uri` object.
|
||||
|
||||
# Forms
|
||||
The `Form` class lets you combine `Field` instances, and decode
|
||||
|
|
|
@ -393,3 +393,37 @@ class MapField extends Field<Map<String, dynamic>> {
|
|||
return form.readFromMap(mapValue);
|
||||
}
|
||||
}
|
||||
|
||||
/// A [Field] that parses plain text as a [Uri].
|
||||
class UriField extends Field<Uri> {
|
||||
// Reuse text validation logic.
|
||||
TextField _textField;
|
||||
|
||||
UriField(String name,
|
||||
{String label, String type = 'url', bool isRequired = true})
|
||||
: super(name, type, label: label, isRequired: isRequired) {
|
||||
_textField = TextField(name, label: label, isRequired: isRequired);
|
||||
}
|
||||
|
||||
@override
|
||||
FutureOr<U> accept<U>(FormRenderer<U> renderer) =>
|
||||
renderer.visitUriField(this);
|
||||
|
||||
@override
|
||||
FutureOr<FieldReadResult<Uri>> read(
|
||||
Map<String, dynamic> fields, Iterable<UploadedFile> files) async {
|
||||
var result = await _textField.read(fields, files);
|
||||
if (result == null) {
|
||||
return null;
|
||||
} else if (result.isSuccess != true) {
|
||||
return FieldReadResult.failure(result.errors);
|
||||
} else {
|
||||
var value = Uri.tryParse(result.value);
|
||||
if (value != null) {
|
||||
return FieldReadResult.success(value);
|
||||
} else {
|
||||
return FieldReadResult.failure(['"$name" must be a valid URI.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,4 +20,6 @@ abstract class FormRenderer<T> {
|
|||
FutureOr<T> visitTextField(TextField field);
|
||||
|
||||
FutureOr<T> visitMapField(MapField field);
|
||||
|
||||
FutureOr<T> visitUriField(UriField field);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue