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.
71 lines
2.1 KiB
71 lines
2.1 KiB
import {infer as inferUtil} from '../../util'
|
|
import {ValidationResult} from "./types";
|
|
|
|
export namespace Cast {
|
|
/** Attempt to infer the native type of a string value. */
|
|
export function infer(fieldName: string, inputValue: any): ValidationResult {
|
|
return {
|
|
valid: true,
|
|
castValue: typeof inputValue === 'string' ? inferUtil(inputValue) : inputValue,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Casts the input value to a boolean.
|
|
* Note that this assumes the value may be boolish. The strings "true", "True",
|
|
* "TRUE", and "1" evaluate to `true`, while "false", "False", "FALSE", and "0"
|
|
* evaluate to `false`.
|
|
* @param fieldName
|
|
* @param inputValue
|
|
*/
|
|
export function boolean(fieldName: string, inputValue: any): ValidationResult {
|
|
let castValue = !!inputValue
|
|
|
|
if ( ['true', 'True', 'TRUE', '1'].includes(inputValue) ) castValue = true
|
|
if ( ['false', 'False', 'FALSE', '0'].includes(inputValue) ) castValue = false
|
|
|
|
return {
|
|
valid: true,
|
|
castValue,
|
|
}
|
|
}
|
|
|
|
/** Casts the input value to a string. */
|
|
export function string(fieldName: string, inputValue: any): ValidationResult {
|
|
return {
|
|
valid: true,
|
|
castValue: String(inputValue),
|
|
}
|
|
}
|
|
|
|
/** Casts the input value to a number, if it is numerical. Fails otherwise. */
|
|
export function numeric(fieldName: string, inputValue: any): ValidationResult {
|
|
if ( !isNaN(parseFloat(inputValue)) ) {
|
|
return {
|
|
valid: true,
|
|
castValue: parseFloat(inputValue)
|
|
}
|
|
}
|
|
|
|
return {
|
|
valid: false,
|
|
message: 'must be numeric',
|
|
}
|
|
}
|
|
|
|
/** Casts the input value to an integer. Fails otherwise. */
|
|
export function integer(fieldName: string, inputValue: any): ValidationResult {
|
|
if ( !isNaN(parseInt(inputValue)) ) {
|
|
return {
|
|
valid: true,
|
|
castValue: parseInt(inputValue)
|
|
}
|
|
}
|
|
|
|
return {
|
|
valid: false,
|
|
message: 'must be an integer',
|
|
}
|
|
}
|
|
}
|