@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
36 lines (35 loc) • 1.3 kB
JavaScript
import formatPhoneNumber, { isValidNumber, } from '../utilities/formatPhoneNumber.js';
import AbstractField from './AbstractField.js';
class PhoneField extends AbstractField {
static generateTemplateDetails(options) {
return {
valueType: `string${options.definition.isArray ? '[]' : ''}`,
};
}
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;