You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ui/src/form/fields/TextInputField.component.ts

106 lines
2.5 KiB

import {Attribute, Component, Element} from '../../decorators.js'
import {InputComponent} from './Input.component.js'
@Component('ex-input')
export class TextInputFieldComponent extends InputComponent {
protected static styles = `
<style>
label {
display: flex;
flex-direction: column;
margin: 20px;
}
small.error {
margin-top: 3px;
color: var(--color-danger);
}
</style>
`
protected static html = `
<label>
<span class="label"></span>
<input class="input" type="text">
<small class="error"></small>
</label>
`
@Attribute()
public name?: string
@Attribute()
public placeholder?: string
@Attribute()
public label?: string
@Attribute()
public error?: string
@Attribute()
public minlength?: string
@Attribute()
public maxlength?: string
@Element('span.label')
protected labelEl!: HTMLSpanElement
@Element('input.input')
protected inputEl!: HTMLInputElement
@Element('small.error')
protected errorEl!: HTMLElement
render() {
super.render()
this.labelEl.innerText = this.label || ''
this.inputEl.setAttribute('placeholder', this.placeholder || '')
this.inputEl.setAttribute('name', this.name || this.uuid)
if ( this.hasAttribute('required') ) {
this.inputEl.setAttribute('required', '1')
} else {
this.inputEl.removeAttribute('required')
}
this.errorEl.hidden = !this.error
this.errorEl.innerText = this.error || ''
}
getFieldName(): string {
return this.name || this.uuid
}
getValue(): any {
return this.inputEl.value
}
validate(): boolean {
const isValid = (
!this.hasAttribute('required')
|| this.getValue().trim()
)
if ( !isValid ) {
this.error = 'This field is required'
} else {
this.error = ''
}
const min = parseInt(this.minlength || '', 10)
if ( this.minlength && !isNaN(min) && String(this.getValue()).length < min ) {
this.error = `Value must be at least ${min} characters`
}
const max = parseInt(this.maxlength || '', 10)
if ( this.maxlength && !isNaN(max) && String(this.getValue()).length > max ) {
this.error = `Value must be at most ${max} characters`
}
return isValid
}
}