Skip to content
rsamec edited this page Jul 24, 2014 · 1 revision

Basic usage

1. First define data structure

    //data structure
    interface IPerson{
        FirstName:string;
        LastName:string;
    }

2. Define business rules

    //create new validator for object with structure<IPerson>
    var personValidator = new Validation.AbstractValidator<IPerson>();

    //basic validators
    var required =new Validation.RequiredValidator();
    var maxLength = new Validation.MaxLengthValidator(15);

    //assigned validators to property
    personValidator.RuleFor("FirstName", required);
    personValidator.RuleFor("FirstName",maxLength);

    //assigned validators to property
    personValidator.RuleFor("LastName", required);
    personValidator.RuleFor("LastName",maxLength);

3. Use validation engine

   //concrete validator
   var concreteValidator = personValidator.CreateRule("Data");

   //sample data with errors
   var data = {
           FirstName : "",
           LastName: "Toooooooooooooooooooooooooooooooo long name"
   };

   //validate
   var result = concreteValidator.Validate(data);

   //verify by return result
   expect(result.HasErrors).to.equal(true);
   if (result.HasErrors) console.log(result.ErrorMessage);

   //verify by concrete validator properties
   expect(concreteValidator.ValidationResult.HasErrors).to.equal(true);
   if (concreteValidator.ValidationResult.HasErrors) console.log(concreteValidator.ValidationResult.ErrorMessage);

   //validator properties enables to check specific rule errors
   expect(concreteValidator.Rules["FirstName"].ValidationFailures["required"].HasError).to.equal(true);
   expect(concreteValidator.Rules["FirstName"].ValidationFailures["maxlength"].HasError).to.equal(false);
   expect(concreteValidator.Rules["LastName"].ValidationFailures["required"].HasError).to.equal(false);
   expect(concreteValidator.Rules["LastName"].ValidationFailures["maxlength"].HasError).to.equal(true);