I have a custom text-field component which encapsulates mdl textfield. I am passing desired value through its bindable property. I want to declare (and validate) validation rules in common view model and then pass possible validation error to each text-field (Which should display it however it wants).
my current pseudocode:
<template>
<text-field
value.two-way="entity.value1">
</text-field>
<text-field
value.two-way="entity.value2">
</text-field>
</template>
How can I pass validation error for value1 into first textfield and validation error for value2 into second?
The best i was able to do was:
<template>
<div validation-errors.bind="firstValidationErrors">
<text-field
value.two-way="entity.value1"
errors.bind="firstValidationErrors">
</text-field>
<div>
<div validation-errors.bind="secondValidationErrors">
<text-field
value.two-way="entity.value2"
errors.bind="secondValidationErrors">
</text-field>
<div>
</template>
But I have to create each validation errors array in viewmodel (I am not sure if I really have to but linting forces me to). And also I have to wrap every control in my page. Is there a better way?
Can I do something like this?
<template>
<text-field
value.two-way="entity.value1"
validation-errors.bind="firstValidationErrors"
errors.bind="firstValidationErrors">
</text-field>
<text-field
value.two-way="entity.value2"
validation-errors.bind="secondValidationErrors"
errors.bind="secondValidationErrors">
</text-field>
</template>
Since you want your text-field
to have full control over displaying the errors, why not just make that into a validation renderer ?
It's quite straightforward:
Inject ValidationController
and Element
into your custom element via the constructor
On bind()
you register it like so: this.controller.addRenderer(this);
On unbind()
you unregister it like so: this.controller.removeRenderer(this);
Implement the render
method like so:
public render(instruction: RenderInstruction) { for (const { result } of instruction.unrender) { const index = this.errors.findIndex(x => x.error === result); if (index !== -1) { this.errors.splice(index, 1); } } for (const { result, elements } of instruction.render) { if (result.valid) { continue; } const targets = elements.filter(e => this.element.contains(e)); if (targets.length) { this.errors.push({ error: result, targets }); } } }
That gives you the errors in your custom element. You might as well just directly do the rendering there though.
Note that this example I'm giving you is pretty much a copy-paste from the validation-errors
custom attribute source
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.