Forked from jdanyow/bootstrap-validation\bootstrap-form-validation-renderer.js
Last active
May 12, 2018 21:39
-
-
Save alexsaare/dd35f48dd5d1b4904444e3ab80c66b93 to your computer and use it in GitHub Desktop.
Aurelia - bootstrap form validation feature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {BootstrapFormValidationRenderer} from './bootstrap-form-validation-renderer'; | |
export function configure(config) { | |
config.container.registerHandler( | |
'bootstrap-form', | |
container => container.get(BootstrapFormValidationRenderer)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I started to write a BS 4 version, then I found this one. Thank you!