adopted-ember-addons / ember-cp-validations

Ember computed property based validations

Home Page:https://adopted-ember-addons.github.io/ember-cp-validations/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Format validator with number

bmaehr opened this issue · comments

Environment

  • Ember Version: 2.18
  • Ember CLI Version: 2.18
  • Ember CP Validations Version: 3.5.4

Steps to Reproduce

I try to validate the format of a number provided by the user. For example a price like 1.50.

I'm using the format validator to ensure the provided input is in the correct format (e.g. only 2 digits after decimal point). This is working correctly up to the point the data is reloaded from the backend and automatically converted from string to number.

1.) I think in the format validator the value should be always converted to string before doing the regexp on it to avoid this problem.

2.) Could someone give me a hint how it would be possible to change the format validator without a new ember-cp-validations version by using reopen or override or something like this.

validator('format', {
  regex: /^\d+(\.\d{1,2})?$/,
  value(model, attribute) {
    const val = model[attribute];
    return val && val.toString();
  }
})
validator('format', {
  regex: /^\d+(\.\d{1,2})?$/,
  value(model, attribute) {
    const val = model[attribute];
    return val && val.toString();
  }
})

Exactly what I was searching for. Just a small fix:

const val = model.get?model.get(attribute):model[attribute];

@fsmanuel Did you fix it also in ember-cp-validations?

@bmaehr ember-cp-validations uses the validators of ember-validators. You can see the implementation of the format validator here. If you think the value should always be a string you might open an issue over there.