platform/packages/validate/web/main.dart

68 lines
2 KiB
Dart
Raw Normal View History

2021-02-21 02:47:23 +00:00
import 'dart:html';
import 'package:angel_validate/angel_validate.dart';
2021-04-10 12:42:55 +00:00
final $errors = querySelector('#errors') as UListElement?;
final $form = querySelector('#form') as FormElement?;
final $blank = querySelector('[name="blank"]') as InputElement?;
2021-02-21 02:47:23 +00:00
final Validator formSchema = Validator({
'firstName*': [isString, isNotEmpty],
'lastName*': [isString, isNotEmpty],
'age*': [isInt, greaterThanOrEqualTo(18)],
'familySize': [isInt, greaterThanOrEqualTo(1)],
'blank!': []
}, defaultValues: {
'familySize': 1
}, customErrorMessages: {
'age': (age) {
if (age is int && age < 18) {
return 'Only adults can register for passports. Sorry, kid!';
} else if (age == null || (age is String && age.trim().isEmpty)) {
return 'Age is required.';
} else {
return 'Age must be a positive integer. Unless you are a monster...';
}
},
'blank':
"I told you to leave that field blank, but instead you typed '{{value}}'..."
});
main() {
2021-04-10 12:42:55 +00:00
$form!.onSubmit.listen((e) {
2021-02-21 02:47:23 +00:00
e.preventDefault();
2021-04-10 12:42:55 +00:00
$errors!.children.clear();
2021-02-21 02:47:23 +00:00
var formData = {};
['firstName', 'lastName', 'age', 'familySize'].forEach((key) {
formData[key] = (querySelector('[name="$key"]') as InputElement).value;
});
2021-04-10 12:42:55 +00:00
if ($blank!.value!.isNotEmpty) formData['blank'] = $blank!.value;
2021-02-21 02:47:23 +00:00
print('Form data: $formData');
try {
var passportInfo =
formSchema.enforceParsed(formData, ['age', 'familySize']);
2021-04-10 12:42:55 +00:00
$errors!.children
2021-02-21 02:47:23 +00:00
..add(success('Successfully registered for a passport.'))
..add(success('First Name: ${passportInfo["firstName"]}'))
..add(success('Last Name: ${passportInfo["lastName"]}'))
..add(success('Age: ${passportInfo["age"]} years old'))
..add(success(
'Number of People in Family: ${passportInfo["familySize"]}'));
} on ValidationException catch (e) {
2021-04-10 12:42:55 +00:00
$errors!.children.addAll(e.errors.map((error) {
2021-02-21 02:47:23 +00:00
return LIElement()..text = error;
}));
}
});
}
LIElement success(String str) => LIElement()
..classes.add('success')
..text = str;