All files / src/attributes SettingsValidationCustomAttribute.ts

100% Statements 13/13
100% Branches 14/14
100% Functions 2/2
100% Lines 11/11
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48          1x 1x                         1x     1x   36x           8x     8x 1x   7x       8x     8x        
/**
 * @module Attributes
 * 
 */ /** */
 
import { bindable, autoinject } from 'aurelia-framework';
import { FieldSettings } from 'sn-client-js';
 
/**
 * Custom attribute that can be added to an Input field and can be used to validate its value based on a provided sensenet FieldSetting.
 * Usage example:
 * ```html
 * <input type="text" value.bind="value" settings-validation.bind="settings">
 * ```
 * The following attributes will be added when a settings object is bound:
 * 
 * required, minlength, maxlength, pattern
 */
@autoinject
export class SettingsValidationCustomAttribute {
    
    @bindable({primaryProperty: true})
    settings: FieldSettings.FieldSetting;
 
    constructor(private element: Element) {
 
    }
 
    settingsChanged(newSetting: FieldSettings.FieldSetting){
        // Req'd
        newSetting.Compulsory ? this.element.setAttribute('required', 'required') : this.element.removeAttribute('required');
 
        //TextFields - MinLength
        if (FieldSettings.isFieldSettingOfType(newSetting, FieldSettings.TextFieldSetting) && newSetting.MinLength){
            this.element.setAttribute('minlength', newSetting.MinLength.toString())
        } else {
            this.element.removeAttribute('minlength')
        }
 
        //TextFields - MaxLength
        (FieldSettings.isFieldSettingOfType(newSetting, FieldSettings.TextFieldSetting) && newSetting.MaxLength) ? this.element.setAttribute('maxlength', newSetting.MaxLength.toString()) : this.element.removeAttribute('maxlength');
       
        //ShortText - Regex/pattern
        (FieldSettings.isFieldSettingOfType(newSetting, FieldSettings.ShortTextFieldSetting) && newSetting.Regex) ? this.element.setAttribute('pattern', newSetting.Regex) : this.element.removeAttribute('pattern');
 
        //...
    }
}