Hey there!
First of all, I’m new to Aurelia, so it could well be something obvious that I’m missing, so sorry in advance.
I’m trying to implement an input with validation such that if a value typed in is incorrect, it instantly changes to the last correct value (or some other value dictated by the validation logic).
For instance say I have an input of type number, and the validation rule is that the number has to be less than 100. Otherwise, whatever I type gets set to 100.
First I tried making the property @bindable / @observable and watch the PropertyChanged callback. This gives me the old value and new value, so I could easily apply my validation logic, however setting this.property = correctValue this would cause the change callback to be called again, causing an infinite loop (and stack overflow).
The second trick I tried was using a Bidirectional Value Converter. In the fromView method, I checked if the value was greater than 100, and if it was, I would return 100, otherwise return the actual value.
export class MaxNumberValueConverter { fromView(value, maxNumber) { if (parseInt(value) > maxNumber) { return maxNumber; } else { return value; } } }
Strangely, this works the first time I type a wrong value, but after the first correction is applied, the value from the input stops being updated so I can type whatever I want.
Lastly I tried this ugly hack, manually updating the value from the input:
< input type=“text” value.bind=“pageNumber | maxNumber:el:100” ref=“el” / >
export class MaxNumberValueConverter {
fromView(value, el, maxNumber) { if (parseInt(value) > maxNumber) { $(el).val(maxNumber); return maxNumber; } else { return value; } }
}
This works, however:
- I get a feeling this is not the right way to do it
- I can’t get the old value from the input
Any tips are greatly appreciated,
Thanks!