Show:

Validator Class

Defined in: a25_validate.js:27
Module: breeze

Instances of the Validator class provide the logic to validate another object and provide a description of any errors encountered during the validation process. They are typically associated with a 'validators' property on the following types: EntityType, DataProperty or NavigationProperty.

A number of property level validators are registered automatically, i.e added to each DataProperty.validators property based on DataProperty metadata. For example,

  • DataProperty.dataType -> one of the 'dataType' validator methods such as Validator.int64, Validator.date, Validator.bool etc.
  • DataProperty.maxLength -> Validator.maxLength
  • DataProperty.isNullable -> Validator.required (if not nullable)

Item Index

Methods

Properties

Methods

<ctor> Validator

(
  • name
  • validatorFn
  • [context]
)

Defined in a25_validate.js:42

Validator constructor - This method is used to create create custom validations. Several basic "Validator" construction methods are also provided as static methods to this class. These methods provide a simpler syntax for creating basic validations.

However, sometimes a custom validator will be required.

Parameters:

  • name String

    The name of this validator.

  • validatorFn Function

    A function to perform validation.

    validatorFn(value, context)

    • value Object

      Value to be validated

    • context Object

      The same context object passed into the constructor with the following additonal properties if not otherwise specified.

      • value Object
        The value being validated.
      • name String
        The name of the validator being executed.
      • displayName String
        This will be either the value of the property's 'displayName' property or the value of its 'name' property or the string 'Value'
      • messageTemplate String
        This will either be the value of Validator.messageTemplates[ {this validators name}] or null. Validator.messageTemplates is an object that is keyed by validator name and that can be added to in order to 'register' your own message for a given validator. The following property can also be specified for any validator to force a specific errorMessage string
      • [message] String optional
        If this property is set it will be used instead of the 'messageTemplate' property when an error message is generated.
  • [context] Object optional

    A free form object whose properties will made available during the validation and error message creation process. This object will be passed into the Validator's validation function whenever 'validate' is called. See above for a description of additional properties that will be automatically added to this object if not otherwise specified.

Example:

Most validators will be 'property' level validators, like this.

// v is this function is the value to be validated, in this case a "country" string.
var valFn = function (v) {
    if (v == null) return true;
    return (core.stringStartsWith(v, "US"));
};
var countryValidator = new Validator("countryIsUS", valFn, { 
    displayName: "Country", 
    messageTemplate: "'%displayName%' must start with 'US'" 
});

// Now plug it into Breeze.
// Assume em1 is a preexisting EntityManager.
var custType = metadataStore.getEntityType("Customer");
var countryProp = custType.getProperty("Country");
// Note that validator is added to a 'DataProperty' validators collection.
prop.validators.push(countryValidator);

Entity level validators are also possible

function isValidZipCode(value) {
    var re = /^\d{5}([\-]\d{4})?$/;
    return (re.test(value));
}               

// v in this case will be a Customer entity
var valFn = function (v) {
    // This validator only validates US Zip Codes.
    if ( v.getProperty("Country") === "USA") {
        var postalCode = v.getProperty("PostalCode");
        return isValidZipCode(postalCode);
    }
    return true;
};
var zipCodeValidator = new Validator("zipCodeValidator", valFn, 
    { messageTemplate: "For the US, this is not a valid PostalCode" });

// Now plug it into Breeze.
// Assume em1 is a preexisting EntityManager.
var custType = em1.metadataStore.getEntityType("Customer");
// Note that validator is added to an 'EntityType' validators collection.
custType.validators.push(zipCodeValidator);

What is commonly needed is a way of creating a parameterized function that will itself return a new Validator. This requires the use of a 'context' object.

// create a function that will take in a config object
// and will return a validator
var numericRangeValidator = function(context) {
    var valFn = function(v, ctx) {
        if (v == null) return true;
        if (typeof(v) !== "number") return false;
        if (ctx.min != null && v < ctx.min) return false;
        if (ctx.max != null && v > ctx.max) return false;
        return true;
    };
    // The last parameter below is the 'context' object that will be passed into the 'ctx' parameter above
    // when this validator executes. Several other properties, such as displayName will get added to this object as well.
    return new Validator("numericRange", valFn, {
        messageTemplate: "'%displayName%' must be an integer between the values of %min% and %max%",
        min: context.min,
        max: context.max
    });
};
// Assume that freightProperty is a DataEntityProperty that describes numeric values.
// register the validator
freightProperty.validators.push(numericRangeValidator({ min: 100, max: 500 }));

bool

() Validator static

Defined in a25_validate.js:534

Returns a standard boolean data type Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var productType = em1.metadataStore.getEntityType("Product");
var discontinuedProperty - productType.getProperty("Discontinued");
// Validates that the value of the Discontinued property on Product is a boolean
discontinuedProperty.validators.push(Validator.bool());

byte

() Validator static

Defined in a25_validate.js:517

Returns a standard byte data type Validator. (This is a integer between 0 and 255 inclusive for js purposes).

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var orderType = em1.metadataStore.getEntityType("Order");
var freightProperty - orderType.getProperty("Freight");
// Validates that the value of the Freight property on Order is within the range of a 16 bit integer.
// Probably not a very good validation to place on the Freight property.
regionProperty.validators.push(Validator.byte());

date

() Validator static

Defined in a25_validate.js:561

Returns a standard date data type Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var orderType = em1.metadataStore.getEntityType("Order");
var orderDateProperty - orderType.getProperty("OrderDate");
// Validates that the value of the OrderDate property on Order is a date
// Probably not a very good validation to place on the Freight property.
orderDateProperty.validators.push(Validator.date());

duration

() Validator static

Defined in a25_validate.js:418

Returns a ISO 8601 duration string Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var eventType = em1.metadataStore.getEntityType("Event");
var elapsedTimeProperty - eventType.getProperty("ElapsedTime");
// Validates that the value of the ElapsedTime property on Customer is a duration.
elapsedTimeProperty.validators.push(Validator.duration());

getMessage

() String

Defined in a25_validate.js:208

Returns the message generated by the most recent execution of this Validator.

Returns:

String:

Example:

var v0 = Validator.maxLength({ maxLength: 5, displayName: "City" });
v0.validate("adasdfasdf");
var errMessage = v0.getMessage());

guid

() Validator static

Defined in a25_validate.js:398

Returns a Guid data type Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var custType = em1.metadataStore.getEntityType("Customer");
var customerIdProperty - custType.getProperty("CustomerID");
// Validates that the value of the CustomerID property on Customer is a Guid.
customerIdProperty.validators.push(Validator.guid());

int16

() Validator static

Defined in a25_validate.js:501

Returns a standard 16 bit integer data type Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var orderType = em1.metadataStore.getEntityType("Order");
var freightProperty - orderType.getProperty("Freight");
// Validates that the value of the Freight property on Order is within the range of a 16 bit integer.
freightProperty.validators.push(Validator.int16());

int32

() Validator static

Defined in a25_validate.js:486

Returns a standard 32 bit integer data type Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var orderType = em1.metadataStore.getEntityType("Order");
var freightProperty - orderType.getProperty("Freight");
freightProperty.validators.push(Validator.int32());

int64

() Validator static

Defined in a25_validate.js:463

Returns a standard large integer data type - 64 bit - Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var orderType = em1.metadataStore.getEntityType("Order");
var freightProperty - orderType.getProperty("Freight");
// Validates that the value of the Freight property on Order is within the range of a 64 bit integer.
freightProperty.validators.push(Validator.int64());

maxLength

(
  • context
)
Validator static

Defined in a25_validate.js:328

Returns a standard maximum string length Validator; the maximum length must be specified

Parameters:

  • context Object
    • maxLength Integer

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var custType = em1.metadataStore.getEntityType("Customer");
var regionProperty - custType.getProperty("Region");
// Validates that the value of the Region property on Customer will be less than or equal to 5 characters.
regionProperty.validators.push(Validator.maxLength( {maxLength: 5}));

number

() Validator static

Defined in a25_validate.js:438

Returns a standard numeric data type Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var orderType = em1.metadataStore.getEntityType("Order");
var freightProperty - orderType.getProperty("Freight");
// Validates that the value of the Freight property on Order is a number.
freightProperty.validators.push(Validator.number());

register

(
  • validator
)
static

Defined in a25_validate.js:250

Register a validator instance so that any deserialized metadata can reference it.

Parameters:

registerFactory

(
  • validatorFactory
  • name
)
static

Defined in a25_validate.js:260

Register a validator factory so that any deserialized metadata can reference it.

Parameters:

  • validatorFactory Function

    A function that optionally takes a context property and returns a Validator instance.

  • name String

    The name of the validator.

required

() Validator static

Defined in a25_validate.js:304

Returns a standard 'required value' Validator

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var custType = em1.metadataStore.getEntityType("Customer");
var regionProperty - custType.getProperty("Region");
// Makes "Region" on Customer a required property.
regionProperty.validators.push(Validator.required());

string

() Validator static

Defined in a25_validate.js:378

Returns a standard string dataType Validator.

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var custType = em1.metadataStore.getEntityType("Customer");
var regionProperty - custType.getProperty("Region");
// Validates that the value of the Region property on Customer is a string.
regionProperty.validators.push(Validator.string());

stringLength

(
  • context
)
Validator static

Defined in a25_validate.js:351

Returns a standard string length Validator; both minimum and maximum lengths must be specified.

Parameters:

  • context Object
    • maxLength Integer
    • minLength Integer

Returns:

Validator: A new Validator

Example:

// Assume em1 is a preexisting EntityManager.
var custType = em1.metadataStore.getEntityType("Customer");
var regionProperty - custType.getProperty("Region");
// Validates that the value of the Region property on Customer will be 
// between 2 and 5 characters
regionProperty.validators.push(Validator.stringLength( {minLength: 2, maxLength: 5});

validate

(
  • value
  • additionalContext
)
ValidationError | Null

Defined in a25_validate.js:167

Run this validator against the specified value. This method will usually be called internally either automatically by an property change, entity attach, query or save operation, or manually as a result of a validateEntity call on the EntityAspect. The resulting ValidationResults are available via the EntityAspect.getValidationErrors method.

However, you can also call a validator directly either for testing purposes or some other reason if needed.

Parameters:

  • value Object

    Value to validate

  • additionalContext Object

    Any additional contextual information that the Validator can make use of.

Returns:

ValidationError | Null: A ValidationError if validation fails, null otherwise

Example:

// using one of the predefined validators
var validator = Validator.maxLength({ maxLength: 5, displayName: "City" });
// should be ok because "asdf".length < 5
var result = validator.validate("asdf");
ok(result === null);
result = validator.validate("adasdfasdf");
// extract all of the properties of the 'result'
var errMsg = result.errorMessage;
var context = result.context;
var sameValidator = result.validator;

Properties

context

Object

Defined in a25_validate.js:158

The context for this validator.

This object will typically contain at a minimum the following properties. "name", "displayName", and "message" or "messageTemplate". readOnly

messageTemplates

Object static

Defined in a25_validate.js:271

Map of standard error message templates keyed by validator name. You can add to or modify this object to customize the template used for any validation error message.

Example:

// v is this function is the value to be validated, in this case a "country" string.
var valFn = function (v) {
    if (v == null) return true;
    return (core.stringStartsWith(v, "US"));
};
var countryValidator = new Validator("countryIsUS", valFn, { displayName: "Country" }); 
Validator.messageTemplates["countryIsUS", "'%displayName%' must start with 'US'");

This will have a similar effect to this var countryValidator = new Validator("countryIsUS", valFn, { displayName: "Country", messageTemplate: "'%displayName%' must start with 'US'" });

name

String

Defined in a25_validate.js:151

The name of this validator.

readOnly