ValidationRenderer For Custom Elements with two input fields

Trying to setup a month-range-picker using bootstrap-datepicker, I have the following InlineView:

@inlineView(`
<template>
    <div class="col-sm-2">
        <div class="input-group mb-3">
            <input ref="fromDate" type="text" class="form-control form-control-sm kzvwl-datepicker" readonly.bind="readonly" value.bind="valueFrom" />
            <div class="input-group-append">
                <span class="input-group-text" id="basic-addon2"><i class="fa fa-calendar" aria-hidden="true"></i></span>
            </div>
        </div>
    </div>
    <div class="col-sm-2">
        <div class="input-group mb-3">
            <input ref="toDate" type="text" class="form-control form-control-sm kzvwl-datepicker" readonly.bind="readonly" value.bind="valueTo" start-date.bind="valueFrom" />
            <div class="input-group-append">
                <span class="input-group-text" id="basic-addon2"><i class="fa fa-calendar" aria-hidden="true"></i></span>
            </div>
        </div>
    </div>
</template>
`)

Now my problem is, that I have no clue how to write the ValidationRenderer to set a class “.is-invalid” to the respective input field (one of the two).

With <date-range-picker value.bind="value & validateOnChange") I only get the anchor for the total template including both input fields. Calling element.previousElementSibling I only can access the last input field of the both.

Following my try that works for all input fields but my custom element date-range-picker:

add(element: Element, result: ValidateResult) {
    console.log($(element));

    toastr.options = this.toastrOptions;
    if (!result.valid) {
      if (element.nodeType === 8) element = element.previousElementSibling; //Validation for custom elements like datepicker
      toastr.error(result.message);
      element.classList.add('is-invalid');
    }
  }

Does anyone have a clean solution for that?

@SNO

Here is a form validator I put together. Look at the custom validator towards the bottom of the class

Having validation renderer decide how to display errors is separating validation from an element, which I think is a mistake.

What I’ve done for the aurelia materialize bridge is a custom validation renderer which looks for certain methods added to the custom elements. If those methods exist they are getting called. Since the methods “belong” to the element’s view model they are in full control of the DOM and element’s state.

and one of the elements

Look at the mdRenderValidateResults and mdUnrenderValidateResults methods.
This approach works especially well with custom elements. There is still some default behaviour for a standard input element.

1 Like