drails_validator 2.0.0

  • README.md
  • CHANGELOG.md
  • Installing
  • Versions
  • 46

Build
Status

Library for validate models similar to JPA Bean validation. It provides a way to validate a dart object using constraints which we can use for validation. To check if the object is valid we need to invoke the function validate which returns an Object of type ValidationResult which contains a map of errors for every attribute of the object, for example:

  • Create a new dart project

  • Add dependencies to pubspec.yaml

...
dependencies:
  ...
  drails_validator: ^0.1.0 #change it for the latest version
  ...

dev_dependencies:
  ...
  build_runner: any
  ...
  • Create/edit the file main.dart in the folder bin and put next code on it:
// Copyright (c) 2015, Luis Vargas. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

library Validator.example;

import 'package:intl/intl.dart';
import 'package:validators/validators.dart' as validator;
import 'package:drails_validator/drails_validator.dart';

part 'main.g.dart';

enteredEmailInvalidMessage() =>
    Intl.message('The entered email is invalid', name: 'enteredEmailInvalidMessage');

valueAfterNowAreNotAllowedMessage() => Intl.message('Values after now are not allowed', name: 'valueAfterNowAreNotAllowedMessage');

enteredSSNInvalidMessage() => Intl.message('The entered SSN is invalid', name: 'enteredSSNInvalidMessage');

fieldBShouldNotBeNullIfFieldAGt123Message() => Intl.message("fieldB should not be null if fieldA is greater than 123", name: 'fieldBShouldNotBeNullIfFieldAGt123Message');

bool lowerThanOrEqualNow(DateTime dateOfBirth) => !dateOfBirth.isAfter(new DateTime.now());

bool isSSN(String ssn) => validator.matches(ssn, r'\d\d\d-\d\d-\d\d\d\d');

bool isEmail(String email) => isNotNull(email) && validator.isEmail(email);

_fieldAGt123(Person p) => p.fieldA != null && p.fieldA > 123;

@serializable
class Person extends _$PersonSerializable {
  int id;

  @Length(min: 2)
  String firstName;

  @Length(min: 2)
  String lastName;

  @ValidIf(isEmail, description: enteredEmailInvalidMessage)
  String email;

  @ValidIf(lowerThanOrEqualNow, description: valueAfterNowAreNotAllowedMessage)
  DateTime dateOfBirth;

  @ValidIf(isSSN, description: enteredSSNInvalidMessage)
  String ssn;

  int fieldA;

  @NotNull(iff: _fieldAGt123, description: fieldBShouldNotBeNullIfFieldAGt123Message)
  int fieldB;
}

main() async {
  _initMirrors();


  var invalidPerson = new Person()
        ..id = 1
        ..firstName = ''
        ..lastName = ''
        ..dateOfBirth = new DateTime(2030, 11, 9)
        ..ssn = '123',
      validPerson = new Person()
        ..id = 2
        ..firstName = 'Joe'
        ..lastName = 'Doe'
        ..email = 'joedoe@email.com'
        ..dateOfBirth = new DateTime(1989, 11, 9)
        ..ssn = '123-45-6789';

  print('invalidPerson: ${validate(invalidPerson)}');
  print('validPerson: ${validate(validPerson)}');
}
  • run pub run build_runner build. Then you will see that the file bin/drails_validator_sample.g.dart has been generated and it will contains the next code:
// GENERATED CODE - DO NOT MODIFY BY HAND

part of Validator.example;

// **************************************************************************
// DsonGenerator
// **************************************************************************

abstract class _$PersonSerializable extends SerializableMap {
  int get id;
  String get firstName;
  String get lastName;
  String get email;
  DateTime get dateOfBirth;
  String get ssn;
  int get fieldA;
  int get fieldB;
  void set id(int v);
  void set firstName(String v);
  void set lastName(String v);
  void set email(String v);
  void set dateOfBirth(DateTime v);
  void set ssn(String v);
  void set fieldA(int v);
  void set fieldB(int v);

  operator [](Object __key) {
    switch (__key) {
      case 'id':
        return id;
      case 'firstName':
        return firstName;
      case 'lastName':
        return lastName;
      case 'email':
        return email;
      case 'dateOfBirth':
        return dateOfBirth;
      case 'ssn':
        return ssn;
      case 'fieldA':
        return fieldA;
      case 'fieldB':
        return fieldB;
    }
    throwFieldNotFoundException(__key, 'Person');
  }

  operator []=(Object __key, __value) {
    switch (__key) {
      case 'id':
        id = __value;
        return;
      case 'firstName':
        firstName = __value;
        return;
      case 'lastName':
        lastName = __value;
        return;
      case 'email':
        email = __value;
        return;
      case 'dateOfBirth':
        dateOfBirth = fromSerializedDateTime(__value);
        return;
      case 'ssn':
        ssn = __value;
        return;
      case 'fieldA':
        fieldA = __value;
        return;
      case 'fieldB':
        fieldB = __value;
        return;
    }
    throwFieldNotFoundException(__key, 'Person');
  }

  Iterable<String> get keys => PersonClassMirror.fields.keys;
}

// **************************************************************************
// MirrorsGenerator
// **************************************************************************

_Person__Constructor([positionalParams, namedParams]) => new Person();

const $$Person_fields_id = const DeclarationMirror(name: 'id', type: int);
const $$Person_fields_firstName = const DeclarationMirror(
    name: 'firstName',
    type: String,
    annotations: const [
      const Length(min: 2, max: null, description: lengthShouldBeBetweenMessage)
    ]);
const $$Person_fields_lastName = const DeclarationMirror(
    name: 'lastName',
    type: String,
    annotations: const [
      const Length(min: 2, max: null, description: lengthShouldBeBetweenMessage)
    ]);
const $$Person_fields_email = const DeclarationMirror(
    name: 'email',
    type: String,
    annotations: const [
      const ValidIf(isEmail, description: enteredEmailInvalidMessage, iff: null)
    ]);
const $$Person_fields_dateOfBirth = const DeclarationMirror(
    name: 'dateOfBirth',
    type: DateTime,
    annotations: const [
      const ValidIf(lowerThanOrEqualNow,
          description: valueAfterNowAreNotAllowedMessage, iff: null)
    ]);
const $$Person_fields_ssn = const DeclarationMirror(
    name: 'ssn',
    type: String,
    annotations: const [
      const ValidIf(isSSN, description: enteredSSNInvalidMessage, iff: null)
    ]);
const $$Person_fields_fieldA =
    const DeclarationMirror(name: 'fieldA', type: int);
const $$Person_fields_fieldB =
    const DeclarationMirror(name: 'fieldB', type: int, annotations: const [
  const NotNull(
      description: fieldBShouldNotBeNullIfFieldAGt123Message, iff: _fieldAGt123)
]);

const PersonClassMirror =
    const ClassMirror(name: 'Person', constructors: const {
  '': const FunctionMirror(name: '', $call: _Person__Constructor)
}, fields: const {
  'id': $$Person_fields_id,
  'firstName': $$Person_fields_firstName,
  'lastName': $$Person_fields_lastName,
  'email': $$Person_fields_email,
  'dateOfBirth': $$Person_fields_dateOfBirth,
  'ssn': $$Person_fields_ssn,
  'fieldA': $$Person_fields_fieldA,
  'fieldB': $$Person_fields_fieldB
}, getters: const [
  'id',
  'firstName',
  'lastName',
  'email',
  'dateOfBirth',
  'ssn',
  'fieldA',
  'fieldB'
], setters: const [
  'id',
  'firstName',
  'lastName',
  'email',
  'dateOfBirth',
  'ssn',
  'fieldA',
  'fieldB'
]);

// **************************************************************************
// InitMirrorsGenerator
// **************************************************************************

_initMirrors() {
  initClassMirrors({Person: PersonClassMirror});
}
  • Finally you can run the file bin/drails_validator_sample.dart. If everything is ok you will see next output in console:
invalidPerson: isValid: false, errors: {firstName: [Length should be greather than 2], lastName: [Length should be greather than 2], email: [The entered email is invalid], dateOfBirth: [Values after now are not allowed], ssn: [The entered SSN is invalid]}
validPerson: isValid: true, errors: {}

Add Localization

  • install l10n package by running:
pub global activate l10n
  • generate translations by running:
mkl10n -l es . <path-to-drails_validator-package>

Warning

Remember to replace <path-to-drails_validator-package> by the correct path

mkl10n -l es . <path-to-drails_validator-package>
  • import the generated messages_all.dart file in the main.dart file:
import 'package:drails_validator_example/_l10n/messages_all.dart';

then set the default locale and initialize the messages by adding next code to main function:

main() {
...
  Intl.defaultLocale = 'es';
  await initializeMessages('es');
...
}

final code in main.dart:

// Copyright (c) 2015, Luis Vargas. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

library Validator.example;

import 'package:drails_validator_example/_l10n/messages_all.dart';
import 'package:intl/intl.dart';
import 'package:validators/validators.dart' as validator;
import 'package:drails_validator/drails_validator.dart';

part 'main.g.dart';

enteredEmailInvalidMessage() =>
    Intl.message('The entered email is invalid', name: 'enteredEmailInvalidMessage');

valueAfterNowAreNotAllowedMessage() => Intl.message('Values after now are not allowed', name: 'valueAfterNowAreNotAllowedMessage');

enteredSSNInvalidMessage() => Intl.message('The entered SSN is invalid', name: 'enteredSSNInvalidMessage');

fieldBShouldNotBeNullIfFieldAGt123Message() => Intl.message("fieldB should not be null if fieldA is greater than 123", name: 'fieldBShouldNotBeNullIfFieldAGt123Message');

bool lowerThanOrEqualNow(DateTime dateOfBirth) => !dateOfBirth.isAfter(new DateTime.now());

bool isSSN(String ssn) => validator.matches(ssn, r'\d\d\d-\d\d-\d\d\d\d');

bool isEmail(String email) => isNotNull(email) && validator.isEmail(email);

_fieldAGt123(Person p) => p.fieldA != null && p.fieldA > 123;

@serializable
class Person extends _$PersonSerializable {
  int id;

  @Length(min: 2)
  String firstName;

  @Length(min: 2)
  String lastName;

  @ValidIf(isEmail, description: enteredEmailInvalidMessage)
  String email;

  @ValidIf(lowerThanOrEqualNow, description: valueAfterNowAreNotAllowedMessage)
  DateTime dateOfBirth;

  @ValidIf(isSSN, description: enteredSSNInvalidMessage)
  String ssn;

  int fieldA;

  @NotNull(iff: _fieldAGt123, description: fieldBShouldNotBeNullIfFieldAGt123Message)
  int fieldB;
}

main() async {
  _initMirrors();

  Intl.defaultLocale = 'es';
  await initializeMessages('es');

  var invalidPerson = new Person()
        ..id = 1
        ..firstName = ''
        ..lastName = ''
        ..dateOfBirth = new DateTime(2030, 11, 9)
        ..ssn = '123',
      validPerson = new Person()
        ..id = 2
        ..firstName = 'Joe'
        ..lastName = 'Doe'
        ..email = 'joedoe@email.com'
        ..dateOfBirth = new DateTime(1989, 11, 9)
        ..ssn = '123-45-6789';

  print('invalidPerson: ${validate(invalidPerson)}');
  print('validPerson: ${validate(validPerson)}');
}

Edit the README file

Please don’t edit the README.md file since this one is generated by asciidoctor and pandoc. Instead edit _README.adoc and then run:

asciidoctor _README.adoc

and then:

pandoc -f docbook -t gfm -o README.md _README.adoc

2.0.0

  • support translations

1.0.0

  • upgrade dart sdk to 2.0.0

0.2.0

  • rename customDescription to description in annotations
  • rename description to defaultDescription in annotations
  • add iff method to annotations
  • add typedef IfFunction for iff method

0.1.0

0.0.2

  • add reflectable ''>=0.3.2 <0.4.0"
  • upgrade drails_commons ^0.0.6
  • add Matches annotation
  • add test library and remove unittest

0.0.1

  • Initial version, created by Stagehand

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  drails_validator: ^2.0.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:drails_validator/drails_validator.dart';
  
Version Uploaded Documentation Archive
2.0.0 Sep 28, 2018 Go to the documentation of drails_validator 2.0.0 Download drails_validator 2.0.0 archive
1.0.0+1 Sep 18, 2018 Go to the documentation of drails_validator 1.0.0+1 Download drails_validator 1.0.0+1 archive
1.0.0 Sep 18, 2018 Go to the documentation of drails_validator 1.0.0 Download drails_validator 1.0.0 archive
0.2.0 Jun 15, 2017 Go to the documentation of drails_validator 0.2.0 Download drails_validator 0.2.0 archive
0.1.0 May 16, 2017 Go to the documentation of drails_validator 0.1.0 Download drails_validator 0.1.0 archive
0.0.2 Nov 18, 2015 Go to the documentation of drails_validator 0.0.2 Download drails_validator 0.0.2 archive
0.0.1 Mar 23, 2015 Go to the documentation of drails_validator 0.0.1 Download drails_validator 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
0
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
46
Learn more about scoring.

We analyzed this package on Oct 10, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.4

Platforms

Detected platforms: Flutter, web, other

No platform restriction found in primary library package:drails_validator/drails_validator.dart.

Health suggestions

Format lib/drails_validator.dart.

Run dartfmt to format lib/drails_validator.dart.

Format lib/src/annotations.dart.

Run dartfmt to format lib/src/annotations.dart.

Format lib/src/messages.dart.

Run dartfmt to format lib/src/messages.dart.

Format lib/src/validator_base.dart.

Run dartfmt to format lib/src/validator_base.dart.

Maintenance suggestions

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Maintain an example.

None of the files in your example/ directory matches a known example patterns. Common file name patterns include: main.dart, example.dart or you could also use drails_validator.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
dson ^0.15.0 0.15.1
intl ^0.15.7 0.15.7
validators ^1.0.0 1.0.0+1
Transitive dependencies
analyzer 0.32.6 0.33.0
args 1.5.0
async 2.0.8
boolean_selector 1.0.4
build 0.12.8 1.0.1
built_mirrors_core 0.10.0
charcode 1.1.2
collection 1.14.11
convert 2.0.2
crypto 2.0.6
csslib 0.14.6
dart_style 1.1.3 1.2.0
dson_core 0.15.1
front_end 0.1.4+2 0.1.6
glob 1.1.7
html 0.13.3+3
http 0.12.0
http_multi_server 2.0.5
http_parser 3.1.3
io 0.3.3
js 0.6.1+1
json_rpc_2 2.0.9
kernel 0.3.4+2 0.3.6
logging 0.11.3+2
matcher 0.12.3+1 0.12.4
meta 1.1.6
mime 0.9.6+2
multi_server_socket 1.0.2
node_preamble 1.4.4
package_config 1.0.5
package_resolver 1.0.6
path 1.6.2
plugin 0.2.0+3
pool 1.3.6
pub_semver 1.4.2
serializable_core 0.11.0+1
shelf 0.7.3+3
shelf_packages_handler 1.0.4
shelf_static 0.2.8
shelf_web_socket 0.2.2+4
source_gen 0.9.1+3
source_map_stack_trace 1.1.5
source_maps 0.10.8
source_span 1.4.1
stack_trace 1.9.3
stream_channel 1.6.8
string_scanner 1.0.4
term_glyph 1.0.1
typed_data 1.1.6
utf 0.9.0+5
vm_service_client 0.2.6
watcher 0.9.7+10
web_socket_channel 1.0.9
yaml 2.1.15
Dev dependencies
build_runner any
build_test any
intl_translation any
test ^1.3.3 1.3.4