Search code examples
validationbreeze

Breeze custom validation


How do i pass entity reference to Validation Context in breeze when doing conditional validation?

Consider the following scenario:

I have radio button list which is not directly bound to breeze entity but is bound to my view model property. Depending on radio button selection, i want to validate other inputs on the form that are bound to my breeze data entity.

I tried building custom validation on the radio button where my validation function holds reference to the radio button selection in built-in value property of validation context. Now, i am trying to access my entity object in the validation function to evaluate other input of my forms based on radio button selection.


Solution

  • Here's an arbitrary example of max length validation. Use the context to access the entity and add the logic you need after that.

            function maxLengthValidatorFn(value, context) {
               var someValue = context.entity.SomeProperty;
               //Do something with some value.
               if (value && value.length > context.maxLength)
              return false;
               return true;
            }
    
            function maxLengthValidatorFactory(context) {
                return new breeze.Validator(
                    "maxLength",
                    maxLengthValidatorFn,
                    { messageTemplate: "'%hrn%' exceeds maximum character length of %maxLength%", hrn: context.propertyLabel, maxLength: context.maxLength }
                );
            }