What's the best practice for handling validation on multiple custom elements?

I’m sorry for the perhaps lame title, but here it is.

I have a list of custom elements of the same type, which has a lot of input fields.

For example, my view has:

<my-custom-element transaction.bind="transaction" repeat.for="transaction in transactions"></my-custom-element>
<button click.bind="save">Save transactions</button>

And my custom element looks something like:

	<input type="text" value.bind="transaction.name"/>
	<input type="text" value.bind="transaction.age" />

I wan’t to handle validation and dirty checking on my custom element, as I think it is the most appropriate.

However, what’s the best way to let my view know wheter theres any dirty transactions or invalid transactions?

I have thinked of passing a common object to all of the my-custom-elements, and then passing in a local ID and any validation errors, and let the view handle it, by disabling the save button for example, and letting the save-function clear the dirty flag of each row.

Is this even remotely the best practice, or what is considered the best practice for my problem?

Many thanks in advance!

Add view-model.ref=“my-custom-element” to your element. Then from the parent, you can call myCustomElement.controller.validate()

Hi @zyberzero!

I was surprised at the lack of a “form.dirty” flag when I started using Aurelia, but with a bit of a change of mindset I haven’t had the need. So the answer is “it depends” on exactly what you want the view to do with that information.

For example, if you want to show an error count in each custom element (think of a wizard / tabbed control with a count of errors in each tab header) then you can do that easily with the validation-errors custom attribute.

If you just want a red box around the invalid fields then just use value.bind="transaction.name & validate"in the custom element, and the parent control validator will validate those properties for you (in this case I would put ValidationRules inside your my-custom-element view model).

If you still need a form.dirty flag, there is some discussion of how to do it here: https://github.com/aurelia/templating-resources/issues/160

Let me know if you want some clarification on these ideas - hope it helps!


1 Like

I don’t think there’s any need to do this. The parent validator will do this anyway, if setup properly. The child control can also hook into a validation event. This decouples the controls a bit better than explicitly calling functions of the child/parent, IMHO :slight_smile: