Centralize Aurelia validation logic

女生的网名这么多〃 提交于 2019-12-25 04:09:02

问题


I would like to centralize validation logic in @ensure but I am not sure how to do it. This is an example from documentation:

import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';

export class Person {
  static inject() { return [Validation];}
  
  //I want to inject validation logic here instead of using function(it){...}
  @ensure(function(it){ it.isNotEmpty().hasLengthBetween(3,10) })
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}

And I would to change the code above to like below:

import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import {UserValidation} from 'user/userValidation'; //custom validation logic here

export class Person {
  static inject() { return [Validation];}
  
  //can I do something like this instead of using function(it){...}?
  @ensure(UserValidation.firstName)
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}

If we need to collect first name only on 1 page then we don't have to do this at all but since we might have to have user to enter their first name on multiple different pages, we would like to centralize the validation logic somewhere so that we don't have to copy & paste it everywhere. We don't want to create "first name component" either because UI will be different on each page, so we just want to reuse the validation logic.

UPDATE: I asked this question in Aurelia discussion and was asked to try the following.

//userValidation.js
export function firstName(it){ it.isNotEmpty().hasLengthBetween(3,10)};

import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import * as userValidation from 'user/userValidation';

export class Person {
  static inject() { return [Validation];}
  
  @ensure(userValidation.firstName)
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}

But I am getting this error: Unhandled promise rejection Error: Error instantiating Person. Any idea how I can fix this?


回答1:


Actually, the following code worked!

//userValidation.js
export function firstName(it){ it.isNotEmpty().hasLengthBetween(3,10)};

//person.js
import {Validation} from 'aurelia-validation';
import {ensure} from 'aurelia-validation';
import * as userValidation from 'user/userValidation';

export class Person {
  static inject() { return [Validation];}
  
  @ensure(userValidation.firstName)
    firstName = 'John';

  constructor(validation) {
    this.validation = validation.on(this);
  }
}


来源:https://stackoverflow.com/questions/32490823/centralize-aurelia-validation-logic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!