@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
41 lines (40 loc) • 1.5 kB
JavaScript
import formatPhoneNumber, { isValidNumber, } from '../utilities/formatPhoneNumber.js';
import AbstractField from './AbstractField.js';
class PhoneField extends AbstractField {
static generateTemplateDetails(options) {
const { definition, language } = options;
const { isArray } = definition;
const arrayNotation = isArray ? '[]' : '';
return {
valueType: language === 'go'
? `${arrayNotation}string`
: `string${arrayNotation}`,
};
}
toValueType(value) {
const stringValue = `${value}`;
const phoneNumber = formatPhoneNumber(stringValue);
return phoneNumber;
}
validate(value, options) {
const errors = super.validate(value, options);
if (errors.length === 0 && this.isRequired && `${value}`.length === 0) {
errors.push({
code: 'MISSING_PARAMETER',
label: this.label,
name: this.name,
});
}
else if (errors.length === 0 && value && !isValidNumber(value)) {
errors.push({
code: 'INVALID_PARAMETER',
name: this.name,
label: this.label,
friendlyMessage: `Please enter a valid phone number.`,
});
}
return errors;
}
}
PhoneField.description = 'Takes anything close to a phone number and formats it. Also great at validating numbers.';
export default PhoneField;