drails_validator 0.2.0

  • README.md
  • CHANGELOG.md
  • Installing
  • Versions
  • 23

drails_validator

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 this one returns an Object of type ValidationResult which contains a map of errors for every attribute of the object, for example:

  1. Create a new dart project

  2. Add dependencies to pubspec.yaml

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

3.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:validator/validator.dart' as validator;
import 'package:drails_validator/drails_validator.dart';

part 'drails_validator_sample.g.dart';

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: 'The entered email is invalid')
  String email;

  @ValidIf(lowerThanOrEqualNow, description: 'Values after now are not allowed')
  DateTime dateOfBirth;

  @ValidIf(isSSN, description: 'The entered SSN is invalid')
  String ssn;

  int fieldA;

  @NotNull(iff: _fieldAGt123, description: "fieldB should not be null if fieldA is greater than 123")
  int fieldB;
}

main() {
  _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)}');
}

  1. create a file in tool folder called build.dart and put next code on it:
import 'package:build_runner/build_runner.dart';
import 'package:dson/phase.dart';


main() async {
  await build(new PhaseGroup()
    ..addPhase(
      // In next line replace `example/**.dart` for the globs you want to use as input, for example `**/*.dart`
      // to take all the dart files of the project as input.
        dsonPhase(const ['example/**.dart'])),
      deleteFilesByDefault: true);
}
  1. run tool/build.dart. 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;

// **************************************************************************
// Generator: InitMirrorsGenerator
// Target: library Validator.example
// **************************************************************************

_initMirrors() {
  initClassMirrors({Person: PersonClassMirror});
  initFunctionMirrors({});
}

// **************************************************************************
// Generator: DsonGenerator
// Target: class Person
// **************************************************************************

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 = 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;
}

_Person__Constructor(params) => new Person();

const $$Person_fields_id = const DeclarationMirror(type: int);
const $$Person_fields_firstName = const DeclarationMirror(
    type: String,
    annotations: const [const Length(min: 2, max: null, description: null)]);
const $$Person_fields_lastName = const DeclarationMirror(
    type: String,
    annotations: const [const Length(min: 2, max: null, description: null)]);
const $$Person_fields_email = const DeclarationMirror(
    type: String,
    annotations: const [
      const ValidIf(isEmail,
          description: r'The entered email is invalid', iff: null)
    ]);
const $$Person_fields_dateOfBirth =
    const DeclarationMirror(type: DateTime, annotations: const [
  const ValidIf(lowerThanOrEqualNow,
      description: r'Values after now are not allowed', iff: null)
]);
const $$Person_fields_ssn =
    const DeclarationMirror(type: String, annotations: const [
  const ValidIf(isSSN, description: r'The entered SSN is invalid', iff: null)
]);
const $$Person_fields_fieldA = const DeclarationMirror(type: int);
const $$Person_fields_fieldB =
    const DeclarationMirror(type: int, annotations: const [
  const NotNull(
      description: r'fieldB should not be null if fieldA is greater than 123',
      iff: _fieldAGt123)
]);

const PersonClassMirror =
    const ClassMirror(name: 'Person', constructors: const {
  '': const FunctionMirror(parameters: const {}, 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'
]);

  1. 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: {}

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

1. Depend on it

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


dependencies:
  drails_validator: "^0.2.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 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
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

Analysis

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

  • Dart: 2.0.0-dev.49.0
  • pana: 0.10.6

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
0 / 100
Health:
Code health derived from static analysis. [more]
14 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
95 / 100
Overall score:
Weighted score of the above. [more]
23
Learn more about scoring.

Platforms

Detected platforms: Flutter, web, other

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

Suggestions

  • Fix analysis and formatting issues.

    Analysis or formatting checks reported 9 errors 2 hints.

    Strong-mode analysis of lib/src/annotations.dart failed with the following error:

    line: 106 col: 3
    Invalid override. The type of 'NotNull.iff' ('() → Function') isn't a subtype of 'ValidIf.iff' ('() → (dynamic) → bool').

    Strong-mode analysis of lib/src/validator_base.dart failed with the following error:

    line: 24 col: 17
    The argument type '(ValidIf) → Null' can't be assigned to the parameter type '(Annotation) → void'.

  • The description is too short.

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

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

  • 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 >=1.8.0 <2.0.0
dson ^0.6.0 0.6.0 0.13.2
validator >=0.0.7 <0.0.9 0.0.7
Transitive dependencies
analyzer 0.30.0+4 0.31.1
args 1.4.2
async 1.13.3 2.0.6
barback 0.15.2+15
build 0.9.3 0.12.2
build_barback 0.3.0 0.5.0+3
built_mirrors 0.2.4 0.8.4
charcode 1.1.1
cli_util 0.1.2+1
code_transformers 0.5.1+4
collection 1.14.9
convert 2.0.1
crypto 2.0.2+1
csslib 0.14.1
dart_style 1.0.9+1 1.0.10
front_end 0.1.0-alpha.4.1 0.1.0-alpha.11
glob 1.1.5
html 0.13.3
http_parser 3.1.1
isolate 1.1.0 2.0.0
kernel 0.3.0-alpha.1.1 0.3.0-alpha.11
logging 0.11.3+1
meta 1.1.2
mime 0.9.6
package_config 1.0.3
path 1.5.1
plugin 0.2.0+2
pool 1.3.4
serializable 0.3.3 0.9.2
shelf 0.6.8 0.7.2
shelf_static 0.2.7
source_gen 0.5.10+1 0.8.1
source_maps 0.10.4
source_span 1.4.0
stack_trace 1.9.2
stream_channel 1.6.5
stream_transform 0.0.11
string_scanner 1.0.2
typed_data 1.1.5
unittest 0.11.7 0.12.4+1
utf 0.9.0+4
watcher 0.9.7+7
yaml 2.1.13
Dev dependencies
build_runner any 0.3.4+1 0.8.3
test any