Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a global validation rule with aurelia-validation

I have code like this:

import {ValidationRules} from 'aurleia-validation'

export class EmailDialog{
    email = null

    activate(item){
       email = item
       ValidationRules.ensure(i => i.emailAddress)
           .required()
           .email()
       ... // other code
    }

I want to add a new .email() validation function that either overrides the existing one or just has a new name (i.e .emailExp()) that is available anywhere in my app that I use ValidationRules.

I have seen code that enables you to add custom rules like so:

ValidationRules.customRule('emailExp',(value,obj) => {},"")

which you can then call with

ValidationRules.ensure(i => i.emailAddress).satisfiesRule('emailExp')

However, I'm not sure where to put that code to make it available globally. Do I simply add the custom rules in the app.js? Will this make the custom rules available to any VM that imports ValidationRules?

Is there a way to extend the fluid API of ValidationRules so that I could do the following:

ValidationRules.ensure(i => i.emailAddress).emailExp()

Thanks for your help.

like image 879
RHarris Avatar asked Dec 05 '25 10:12

RHarris


1 Answers

You'll want to put it in app.js in the constructor. By putting it here, it will be available globally.

You can follow this example from my application:

import { ValidationRules } from 'aurelia-validation';

export class App {

  constructor() {
    ValidationRules.customRule(
      'integerRange',
      (value, obj, min, max) => value === null || value === undefined
        || Number.isInteger(1 * value) && value >= min && value <= max,
      null,
      (min, max) => ({ min, max })
    );
  }
}

Usage (in any viewmodel):

ValidationRules
  .ensure('cat_value_orig').required().maxLength(255)
  .ensure('cat_value_tran').minLength(2).maxLength(255)
  .ensure('cat_order').satisfiesRule('integerRange', 0, 100)
  .on(this);
like image 138
LStarky Avatar answered Dec 08 '25 00:12

LStarky