Listing 6-14: Using a Custom validator to test for a phone number
import PropTypes from 'prop-types';
function Contact(props){
return(
<li>{props.fullName}: {props.phone}</li>
)
}
const isPhoneNumber = function(props, propName, componentName) {
const regex = /^(+d{1,2}s)?(?d{3})?[s.-]d{3}[s.-]d{4}$/;
if (!regex.test(props[propName])) {
return new Error('Expected a phone number.');
}
}
Contact.propTypes = {
fullName: PropTypes.string,
phone: isPhoneNumber,
}
export default Contact;
import PropTypes from 'prop-types';
function Contact(props){
return(
<li>{props.fullName}: {props.phone}</li>
)
}
const isPhoneNumber = function(props, propName, componentName) {
const regex = /^(+d{1,2}s)?(?d{3})?[s.-]d{3}[s.-]d{4}$/;
if (!regex.test(props[propName])) {
return new Error('Expected a phone number.');
}
}
Contact.propTypes = {
fullName: PropTypes.string,
phone: isPhoneNumber,
}
export default Contact;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.