import utilsIsNumber from '@tinkoff/utils/is/number' ; import utilsIsString from '@tinkoff/utils/is/string' ; export type Validator = ( value : string ) => string | boolean ; export const isUrl = ( value ) => { if ( ! value ) { return 'value should not be empty' ; } let url ; try { url = new URL ( value ) ; } catch ( _ ) { return 'URL is not valid' ; } return ( url . protocol !== 'http:' && url . protocol !== 'https:' && `Invalid protocol ${ url . protocol }` ) ; } ; export const isNumber = ( value ) => { if ( ! value ) { return 'value should not be empty' ; } const convertedValue = + value ; if ( utilsIsNumber ( convertedValue ) && ! Number . isNaN ( convertedValue ) ) { return true ; } return 'value is not a number' ; } ; export const isTrue = ( value ) => { if ( ! value ) { return 'value should not be empty' ; } if ( value === 'true' ) { return true ; } return 'value is not a true' ; } ; export const isFalse = ( value ) => { if ( ! value ) { return 'value should not be empty' ; } if ( value === 'false' ) { return true ; } return 'value is not a false' ; } ; export const isOneOf = ( values = [ ] ) : Validator => ( value ) => { if ( ! value ) { return 'value should not be empty' ; } if ( values . indexOf ( value ) !== - 1 ) { return true ; } return 'value is not in list' ; } ; export const startsWith = ( prefix ) : Validator => ( value ) => { if ( ! value ) { return 'value should not be empty' ; } if ( value . startsWith ( prefix ) ) { return true ; } return `value should starts with ${ prefix }` ; } ; export const endsWith = ( postfix ) : Validator => ( value ) => { if ( ! value ) { return 'value should not be empty' ; } if ( value . endsWith ( postfix ) ) { return true ; } return `value should ends with ${ postfix }` ; } ; export const combineValidators = ( validators ) : Validator => ( value ) => { const result = validators . reduce ( ( acc , validator ) => { const currentValidatorResult = validator ( value ) ; if ( utilsIsString ( currentValidatorResult ) ) { return utilsIsString ( acc ) ? `${ acc }; ${ currentValidatorResult }` : currentValidatorResult ; } return utilsIsString ( acc ) ? acc : acc && currentValidatorResult ; } , true ) ; return result ; } ;