97 lines
2.0 KiB
TypeScript
97 lines
2.0 KiB
TypeScript
import { parceable } from "../Schema"
|
|
import SchemaItem from "../SchemaItem"
|
|
|
|
export default class SchemaString extends SchemaItem<string> {
|
|
public id = 'string'
|
|
|
|
public minLength(value: number, message?: string) {
|
|
return this.min(value, message)
|
|
}
|
|
|
|
public maxLength(value: number, message?: string) {
|
|
return this.max(value, message)
|
|
}
|
|
|
|
/**
|
|
* force the input text to be a minimum of `value` size
|
|
* @param value the minimum length of the text
|
|
* @param message the message to display on an error
|
|
*/
|
|
@parceable()
|
|
public min(value: number, message?: string): this {
|
|
this.addValidation({
|
|
fn(input) {
|
|
return input.length >= value
|
|
},
|
|
error: message
|
|
})
|
|
|
|
return this
|
|
}
|
|
|
|
/**
|
|
* transform the final text to the defined casing
|
|
* @param casing the final casing
|
|
*/
|
|
@parceable()
|
|
public toCasing(casing: 'lower' | 'upper'): this {
|
|
const fn: keyof string = casing === 'lower' ? 'toLowerCase' : 'toUpperCase'
|
|
this.addPostProcess((it) => it[fn]())
|
|
|
|
return this
|
|
}
|
|
|
|
/**
|
|
* force the input text to be a maximum of `value` size
|
|
* @param value the maximum length of the text
|
|
* @param message the message to display on an error
|
|
*/
|
|
@parceable()
|
|
public max(value: number, message?: string): this {
|
|
this.addValidation({
|
|
fn(input) {
|
|
return input.length <= value
|
|
},
|
|
error: message
|
|
})
|
|
return this
|
|
}
|
|
|
|
/**
|
|
* the value must not be empty (`''`)
|
|
* @param message
|
|
* @returns
|
|
*/
|
|
@parceable()
|
|
public notEmpty(message?: string): this {
|
|
this.addValidation({
|
|
fn(input) {
|
|
return input !== ''
|
|
},
|
|
error: message
|
|
})
|
|
return this
|
|
}
|
|
|
|
/**
|
|
* force the input text to respect a Regexp
|
|
* @param regex the regex to validate against
|
|
* @param message the message to display on an error
|
|
*/
|
|
@parceable()
|
|
public regex(regex: RegExp, message?: string): this {
|
|
this.addValidation({
|
|
fn(input) {
|
|
return regex.test(input)
|
|
},
|
|
error: message
|
|
})
|
|
return this
|
|
}
|
|
|
|
|
|
public override isOfType(input: unknown): input is string {
|
|
return typeof input === 'string'
|
|
}
|
|
}
|