cosmo-ui
Version:
Common React components
39 lines (35 loc) • 1.18 kB
text/typescript
import * as moment from 'moment'
/**
* A form validator should return a an array of errors
* or an empty array if there are no errors
*/
export type FormValidator = (value: any) => string[]
/**
* Validate a UK postcode using regex
*
* @param postcode
*/
export const validatePostcode: FormValidator = (postcode: string) => {
/* tslint:disable */
const str = '(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9' +
']?)|(([A - Z - [QVX]][0 - 9][A - HJKPSTUW]) | ([A - Z - [QVX]][A - Z - [IJZ]][0 ' +
'- 9][ABEHMNPRVWXY])))) [0 - 9][A - Z - [CIKMOV]]{2 })'
/* tslint:enable */
const regex = new RegExp(str)
if (regex.test(postcode)) {
return []
}
return ['* Not a valid UK postcode']
}
export const INPUT_DATE_FORMAT = 'YYYY-MM-DDTHH:mm'
/**
* Helper function for client's wishing to pre-initialize the value
* This ensures it is in the format required for datetime-local
*
* @param value
*/
export const formatDateForInput = (value: string) => {
const parsed = moment(value)
const formatted = parsed.format(INPUT_DATE_FORMAT)
return formatted === 'Invalid date' ? value : formatted
}