Skip to content

Instantly share code, notes, and snippets.

@cwardzala
Last active June 30, 2022 15:38
Show Gist options
  • Save cwardzala/ce4b3ba03362d2831f99e9079dcc5053 to your computer and use it in GitHub Desktop.
Save cwardzala/ce4b3ba03362d2831f99e9079dcc5053 to your computer and use it in GitHub Desktop.
Yup helper functions.
import {string, addMethod } from 'yup';
/**
* string().isbn()
* @param {String} message message to display when invalid.
*/
// eslint-disable-next-line no-template-curly-in-string
addMethod(string, 'isbn', function (message = '${path} must be a valid ISBN') {
const rISBN = /(?:(?=.{17}$)97[89][ -](?:[0-9]+[ -]){2}[0-9]+[ -][0-9]|97[89][0-9]{10}|(?=.{13}$)(?:[0-9]+[ -]){2}[0-9]+[ -][0-9Xx]|[0-9]{9}[0-9Xx])/;
return this.matches(rISBN, {
name: 'isbn',
message,
excludeEmptyString: false
});
});
/**
* string().phone()
* @param {String} message message to display when invalid.
*/
// eslint-disable-next-line no-template-curly-in-string
addMethod(string, 'phone', function (message = '${path} must be a valid phone number') {
const rPHONE = /^(1\s*[-/.]?)?(\((\d{3})\)|(\d{3}))\s*[-/.]?\s*(\d{3})\s*[-/.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;
return this.matches(rPHONE, {
name: 'phone',
message,
excludeEmptyString: false
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment