Skip to content

Instantly share code, notes, and snippets.

View bettdouglas's full-sized avatar
💭
Available

Douglas Bett bettdouglas

💭
Available
View GitHub Profile
@bettdouglas
bettdouglas / data-types.dart
Created June 19, 2019 09:36
Data types we want to validate
enum DataType {
EMAIL,PHONE,TEXT,INTEGER,NAME
}
class DynamicInput extends StatefulWidget {
final String label,hint;
///type denotes number or string or email
final DataType type;
final TextEditingController controller;
...
}
class _DynamicInputState extends State<DynamicInput>{
flutter_validate: 1.0.0
class TypesValidator extends AbstractValidator<String> { ///the class responsible for validation logic
DataType type; ///The datatype we'll use
String text; ///the text that we'll validate
TypesValidator(this.text, this.type) : super(text);
}
_validator.ruleFor('email', ()=>text)
..notEmpty() // enforces that the email should not be empty
..withMessage('Email cannot be empty') //return message if the email is empty
..emailAddress() //checks if the email is a valid email address -- validation
..withMessage('Enter a valid email'); //return message if email is empty
_validator.ruleFor('name', ()=>text)
..notEmpty()
..withMessage('Please enter a name')
..length(2, 30)
..withMessage('Please enter a reasonable name');
_validator.ruleFor('email', ()=>text)
..notEmpty()
..withMessage('Email cannot be empty')
..emailAddress()
@bettdouglas
bettdouglas / validation function.dart
Last active June 19, 2019 12:33
Function that validates the string
String validate(){
switch (type) {
case DataType.EMAIL:
return validator.validateRuleFor('email').errorText;
break;
case DataType.INTEGER:
return validator.validateRuleFor('int').errorText;
break;
case DataType.TEXT:
return validator.validateRuleFor('text').errorText;
class Validator {
String text; ///the text to validate. This will be the controller.text value
TypesValidator _validator; //the validation object where we'll define our rules on
DataType type; ///the object that will do the validation for us
Validator(this.text,this.type){
_validator = new TypesValidator(text,type); //initialise the object to do validation
this.create(); //define the rules to our validator object which will be a singleton that will handle multi-validation
}
Widget build(BuildContext context) {
return TextFormField(
controller: widget.controller,
keyboardType: keyBoardType(widget.type),
validator: (str)=>validator(str), ///this is a function which returns the error message we defined using the validator object
decoration: InputDecoration(
hintText: widget.hint,
labelText: widget.label,
helperText: widget.hint,
),
String validator(String s) {
var validator = Validator(s,widget.type).validator;
switch (widget.type) {
case DataType.EMAIL:
return validator.validateRuleFor('email').errorText;
break;
case DataType.INTEGER:
return validator.validateRuleFor('int').errorText;
break;
case DataType.TEXT: