Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexsaare/dd35f48dd5d1b4904444e3ab80c66b93 to your computer and use it in GitHub Desktop.
Save alexsaare/dd35f48dd5d1b4904444e3ab80c66b93 to your computer and use it in GitHub Desktop.
Aurelia - bootstrap form validation feature
// For bootstrap 4 and I18N
import { inject } from 'aurelia-framework'
import { RenderInstruction, ValidateResult } from 'aurelia-validation';
import {I18N} from "aurelia-i18n";
@inject(I18N)
export class BootstrapFormRenderer {
public constructor (private i18n : I18N){ }
public render(instruction: RenderInstruction) {
for (let { result, elements } of instruction.unrender) {
for (let element of elements) {
this.remove(element, result);
}
}
for (let { result, elements } of instruction.render) {
for (let element of elements) {
this.add(element, result);
}
}
}
public add(element: Element, result: ValidateResult) {
if (result.valid) {
if (!element.classList.contains('is-invalid')) {
element.classList.add('is-valid');
}
} else {
// add the has-error class to the enclosing form-group div
element.classList.remove('is-valid');
element.classList.add('is-invalid');
// add help-block
const message = document.createElement('div');
message.className = 'help-block invalid-feedback';
message.textContent = this.i18n.tr(result.message);
message.id = `validation-message-${result.id}`;
element.parentNode.insertBefore(message, element.nextSibling);
}
}
public remove(element: Element, result: ValidateResult) {
if (result.valid) {
if (element.classList.contains('is-valid')) {
element.classList.remove('is-valid');
}
} else {
// remove help-block
const message = element.parentElement.querySelector(`#validation-message-${result.id}`);
if (message) {
element.parentElement.removeChild(message);
element.classList.remove('is-invalid');
}
}
}
}
import {BootstrapFormValidationRenderer} from './bootstrap-form-validation-renderer';
export function configure(config) {
config.container.registerHandler(
'bootstrap-form',
container => container.get(BootstrapFormValidationRenderer));
}
@gregoryagu
Copy link

I started to write a BS 4 version, then I found this one. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment