Search code examples
aurelia

Stop Aurelia value converter from updating in case of validation error


Is there any way how to stop value converter from updating in case of validation error? For example consider this simple converter:

export class JsonValueConverter {
    toView(value) {
        return JSON.stringify(value);
    }

    fromView(value) {
        try {
            return JSON.parse(value);
        } catch (e) {}
    }
}

<textarea value.bind="obj | json"></textarea>

Any invalid JSON value entered to the textarea causes obj = undefined. I'd like to keep the last valid value.


Solution

  • Unfortunately a ValueConverter will not help you since it is stateless and was not designed to do what you're trying to do.

    My suggestion would be to check whether or not it successfully parses to a JSON object. If it doesn't, just return the unconverted value by adding return value; to your catch() brackets. Or, if you would prefer to keep it pure, return null;.

    You should also add validation to your form to require a valid input before committing the data. I recommend using Aurelia-validation -- it will work well for you here.

    Finally, you should consider adding a binding behavior to avoid your Value Converter from interfering with your input. You could either add & debounce:1000 to make it only check after 1 second of idle after input, or & updateTrigger:'blur' to wait to validate until after the focus is lost.