Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Validator

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.

Many of these stock validators are inspired by and implemented to conform to the validators defined at http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx

Sometimes a custom validator will be required.

example

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

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", 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

example

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.

example

// 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 a number 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 }));

Breeze substitutes context values and functions for the tokens in the messageTemplate when preparing the runtime error message; 'displayName' is a pre-defined context function that is always available.

Please note that Breeze substitutes the empty string for falsey parameters. That usually works in your favor. Sometimes it doesn't as when the 'min' value is zero in which case the message text would have a hole where the 'min' value goes, saying: "... an integer between the values of and ...". That is not what you want.

To avoid this effect, you may can bake certain of the context values into the 'messageTemplate' itself as shown in this revision to the pertinent part of the previous example:

example

// ... as before // ... but bake the min/max values into the message template. var template = breeze.core.formatString( "'%displayName%' must be a number between the values of %1 and %2", context.min, context.max); return new Validator("numericRange", valFn, { messageTemplate: template, min: context.min, max: context.max });

method

Validator

param

The name of this validator.

param

A function to perform validation.

validatorFn(value, context)

param

Value to be validated

param

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

param

The value being validated.

param

The name of the validator being executed.

param

This will be either the value of the property's 'displayName' property or the value of its 'name' property or the string 'Value'

param

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

param

If this property is set it will be used instead of the 'messageTemplate' property when an error message is generated.

param

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.

dynamic

Hierarchy

  • Validator

Index

Constructors

constructor

Properties

context

currentContext

currentContext: any

name

name: string

valFn

Static double

double: (Anonymous function) = Validator.number

Static int64

int64: (Anonymous function) = Validator.integer

Static makeRegExpValidator

makeRegExpValidator: makeRegExpValidator = makeRegExpValidator

Creates a regular expression validator with a fixed expression. Many of the stock validators are built with this factory method. Their expressions are often derived from https://github.com/srkirkland/DataAnnotationsExtensions/blob/master/DataAnnotationsExtensions You can try many of them at http://dataannotationsextensions.org/

example

// Make a zipcode validator function zipValidator = Validator.makeRegExpValidator( "zipVal, /^\d{5}([-]\d{4})?$/, "The %displayName% '%value%' is not a valid U.S. zipcode"); // Register it. Validator.register(zipValidator); // Add it to a data property. Assume em is a preexisting EntityManager. var custType = em.metadataStore.getEntityType("Customer"); var zipProperty = custType.getProperty("PostalCode"); zipProperty.validators.push(zipValidator);

method

makeRegExpValidator

static
param

name of this validator

param

regular expression to apply

param

default message for failed validations

param

optional parameters to pass through to validation constructor

returns

A new Validator

Static single

single: (Anonymous function) = Validator.number

Methods

getMessage

  • getMessage(): any
  • Returns the message generated by the most recent execution of this Validator.

    example

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

    method

    getMessage

    Returns any

toJSON

  • toJSON(): any

validate

  • 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.

    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;

    method

    validate

    Parameters

    • value: any

      Value to validate

    • Optional additionalContext: any

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

    Returns ValidationError

    A ValidationError if validation fails, null otherwise

Static bool

  • Returns a standard boolean data type 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());

    method

    bool

    static

    Returns Validator

    A new Validator

Static byte

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

    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());

    method

    byte

    static

    Parameters

    • context: any

    Returns Validator

    A new Validator

Static creditCard

  • Returns a credit card number validator Performs a luhn algorithm checksum test for plausability catches simple mistakes; only service knows for sure

    example

    // Assume em is a preexisting EntityManager. var personType = em.metadataStore.getEntityType("Person"); var creditCardProperty = personType.getProperty("creditCard"); // Validates that the value of the Person.creditCard property is credit card. creditCardProperty.validators.push(Validator.creditCard());

    method

    creditCard

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Static date

  • Returns a standard date data type 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());

    method

    date

    static

    Returns Validator

    A new Validator

Static duration

  • Returns a ISO 8601 duration string 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());

    method

    duration

    static

    Returns Validator

    A new Validator

Static emailAddress

  • Returns the email address validator

    example

    // Assume em is a preexisting EntityManager. var personType = em.metadataStore.getEntityType("Person"); var emailProperty = personType.getProperty("email"); // Validates that the value of the Person.email property is an email address. emailProperty.validators.push(Validator.emailAddress());

    method

    emailAddress

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Static fromJSON

  • fromJSON(json: any): any
  • Creates a validator instance from a JSON object or an array of instances from an array of JSON objects.

    method

    fromJSON

    static

    Parameters

    • json: any

      JSON object that represents the serialized version of a validator.

    Returns any

Static guid

  • Returns a Guid data type 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());

    method

    guid

    static

    Returns Validator

    A new Validator

Static int16

  • Returns a standard 16 bit integer data type 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());

    method

    int16

    static

    Parameters

    • context: any

    Returns Validator

    A new Validator

Static int32

  • Returns a standard 32 bit integer data type Validator.

    example

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

    method

    int32

    static

    Parameters

    • context: any

    Returns Validator

    A new Validator

Static integer

  • Returns a standard large integer data type - 64 bit - 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());

    method

    int64

    static

    Parameters

    • context: any

    Returns Validator

    A new Validator

Static maxLength

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

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

    method

    maxLength

    static

    Parameters

    • context: any

    Returns Validator

    A new Validator

Static none

Static number

  • Returns a standard numeric data type 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());

    method

    number

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Static phone

  • Returns the phone validator Provides basic assertions on the format and will help to eliminate most nonsense input Matches: International dialing prefix: {{}, +, 0, 0000} (with or without a trailing break character, if not '+': [-/. ])

    ((+)|(0(\d+)?[-/.\s])) Country code: {{}, 1, ..., 999} (with or without a trailing break character: [-/. ]) [1-9]\d{,2}[-/.\s]? Area code: {(0), ..., (000000), 0, ..., 000000} (with or without a trailing break character: [-/. ]) (((\d{1,6})|\d{1,6})[-/.\s]?)? Local: {0, ...}+ (with or without a trailing break character: [-/. ]) (\d+[-/.\s]?)+\d+

    example

    // Assume em is a preexisting EntityManager. var customerType = em.metadataStore.getEntityType("Customer"); var phoneProperty = customerType.getProperty("phone"); // Validates that the value of the Customer.phone property is phone. phoneProperty.validators.push(Validator.phone());

    method

    phone

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Static register

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

    method

    register

    static

    Parameters

    • validator: Validator

      Validator to register.

    Returns void

Static registerFactory

  • registerFactory(validatorFactory: (options?: any) => Validator, name: string): void
  • Register a validator factory so that any deserialized metadata can reference it.

    method

    registerFactory

    static

    Parameters

    • validatorFactory: (options?: any) => Validator

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

    • name: string

      The name of the validator.

    Returns void

Static regularExpression

  • regularExpression(context?: any): Validator
  • Returns a regular expression validator; the expression must be specified

    example

    // Add validator to a property. Assume em is a preexisting EntityManager. var customerType = em.metadataStore.getEntityType("Customer"); var regionProperty = customerType.getProperty("Region"); // Validates that the value of Customer.Region is 2 char uppercase alpha. regionProperty.validators.push(Validator.regularExpression( {expression: '^[A-Z]{2}$'} );

    method

    regularExpression

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Static required

  • Returns a standard 'required value' 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()); // or to allow empty strings regionProperty.validators.push(Validator.required({ allowEmptyStrings: true }););

    method

    required

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Static string

  • Returns a standard string dataType 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());

    method

    string

    static

    Returns Validator

    A new Validator

Static stringLength

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

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

    method

    stringLength

    static

    Parameters

    • context: any

    Returns Validator

    A new Validator

Static url

  • Returns the URL (protocol required) validator

    example

    // Assume em is a preexisting EntityManager. var personType = em.metadataStore.getEntityType("Person"); var websiteProperty = personType.getProperty("website"); // Validates that the value of the Person.website property is a URL. websiteProperty.validators.push(Validator.url());

    method

    url

    static

    Parameters

    • Optional context: any

    Returns Validator

    A new Validator

Object literals

Static messageTemplates

messageTemplates: object

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'" });

property

messageTemplates {Object}

static

bool

bool: string = "'%displayName%' must be a 'true' or 'false' value"

creditCard

creditCard: string = "The %displayName% is not a valid credit card number"

date

date: string = "'%displayName%' must be a date"

duration

duration: string = "'%displayName%' must be a ISO8601 duration string, such as 'P3H24M60S'"

emailAddress

emailAddress: string = "The %displayName% '%value%' is not a valid email address"

guid

guid: string = "'%displayName%' must be a GUID"

integer

integer: string = "'%displayName%' must be an integer"

integerRange

integerRange: string = "'%displayName%' must be an integer between the values of %minValue% and %maxValue%"

maxLength

maxLength: string = "'%displayName%' must be a string with %maxLength% characters or less"

number

number: string = "'%displayName%' must be a number"

phone

phone: string = "The %displayName% '%value%' is not a valid phone number"

regularExpression

regularExpression: string = "The %displayName% '%value%' does not match '%expression%'"

required

required: string = "'%displayName%' is required"

string

string: string = "'%displayName%' must be a string"

stringLength

stringLength: string = "'%displayName%' must be a string with between %minLength% and %maxLength% characters"

url

url: string = "The %displayName% '%value%' is not a valid url"

Generated using TypeDoc