swannee
swannee

Reputation: 3466

Aurelia validation not binding to textbox component

I've made a simple textbox component that just wraps some styling and a combination of label and textbox. When I attempt to bind validation to this control using the typical binding syntax, the blur functionality isn't causing validation to execute.

The component view looks like:

<template>
    <div class="form-field">
        <div class="form-field__label">
            ${label}
            <input name.bind="name" id.bind="name" class="form-field__input" type.bind="type" value.bind="value" tabindex.bind="tabIndex"></input>
        </div>
    </div>
</template>

And the viewmodel looks like:

import {bindable, bindingMode} from 'aurelia-framework';

export class Textbox {
    @bindable({defaultBindingMode: bindingMode.twoWay}) value : string;
    @bindable label : string;
    @bindable type : string = "textbox";
    @bindable tabIndex: number;
    @bindable hidden : boolean;
    @bindable name : string = '';
}

And the component is used like this:

<textbox value.bind="emailAddress & validate" type="email"></textbox>

The databinding is working as expected, but the validation binding isn't working. Any ideas are appreciated.

Upvotes: 3

Views: 1036

Answers (1)

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

The element needs to fire a blur event. Since your element is custom, you'll need to add code to fire it when it "blurs". In your case, this is pretty simple, there's only one focusable element in your custom element's template.

Here's an example: https://gist.run?id=06bda9ac6e068ad21dab7b470f69c566

textbox.html

<template>
  <div class="form-field">
    <div class="form-field__label">
      ${label}
      <input name.bind="name"
             id.bind="name"
             class="form-field__input"
             type.bind="type"
             value.bind="value"
             tabindex.bind="tabIndex"
             blur.trigger="blur()">
    </div>
  </div>
</template>

textbox.js

import {bindable, bindingMode, DOM, inject} from 'aurelia-framework';

@inject(Element)
export class Textbox {
  @bindable({defaultBindingMode: bindingMode.twoWay}) value: string;
  @bindable label: string;
  @bindable type: string = "textbox";
  @bindable tabIndex: number;
  @bindable hidden: boolean;
  @bindable name: string = '';
  element: Element;

  constructor(element) {
    this.element = element;
  }

  blur() {
    this.element.dispatchEvent(DOM.createCustomEvent('blur'));
  }
}

We'll get this added to the docs: https://github.com/aurelia/validation/issues/297

Upvotes: 5

Related Questions