validate

Undocumented in source. Be warned that the author may not have intended to support it.
  1. void validate(T object)
  2. void validate(T object, string pathPrefix)
    void
    validate
    (
    T
    )
    (
    ref T object
    ,
    string pathPrefix
    )

Examples

validate - Should throw array of ValidationError

import dutils.validation.constraints : ValidateRequired,
  ValidateMinimumLength, ValidateMaximumLength, ValidateMinimum, ValidateEmail;

struct Person {
  @ValidateRequired()
  @ValidateMinimumLength(2)
  @ValidateMaximumLength(100)
  string name;

  @ValidateMinimum!float(20) float height;

  @ValidateEmail()
  string email;

  // TODO: add when recustion is working
  // Person[] children;
}

// TODO: add when recustion is working
// auto person = Person("a", -1, "notanemail", [Person()]);
auto person = Person("a", -1, "notanemail");

auto catched = false;
try {
  validate(person);
} catch (ValidationErrors validation) {
  import std.conv : to;

  catched = true;
  assert(validation.errors.length == 3,
      "expected 3 errors, got " ~ validation.errors.length.to!string
      ~ " with message: " ~ validation.msg);
  assert(validation.errors[0].type == "minimumLength", "expected minimumLength error");
  assert(validation.errors[1].type == "minimum", "expected minimum error");
  assert(validation.errors[2].type == "email", "expected email error");
}

assert(catched == true, "did not catch the expected errors");

validate - Should not throw validation errors

import dutils.validation.constraints : ValidateMinimumLength,
  ValidateMaximumLength, ValidateMinimum, ValidateEmail;

struct Person {
  @ValidateMinimumLength(2)
  @ValidateMaximumLength(100)
  string name;

  @ValidateMinimum!float(20) float height;

  @ValidateEmail()
  string email;
}

Person person;
person.name = "Anna";
person.height = 167;

validate(person);

validate - Should not throw validation errors for nested structs

import dutils.validation.constraints : ValidateRequired,
  ValidateMinimumLength, ValidateMaximumLength, ValidateMinimum, ValidateEmail;

struct Person {
  @ValidateRequired()
  @ValidateMinimumLength(2)
  @ValidateMaximumLength(100)
  string name;

  @ValidateMinimum!float(20) float height;

  @ValidateEmail()
  string email;

  // TODO: add when recustion is working
  // Person[] children;
}

// TODO: add when recustion is working
// Person child;
// child.name = "Sofia";

Person person;
person.name = "Anna";
person.height = 167;
// TODO: add when recustion is working
// person.children ~= child;

validate(person);

Meta