strapi-phone-validator
v0.3.2
Published
Strapi maintaned Custom Fields
Downloads
452
Maintainers
Readme
Strapi-Phone-Validator
Strapi Phone Validator is a powerful and easy-to-use plugin designed to validate phone numbers in various formats. With support for international phone numbers, it offers comprehensive validation to ensure the accuracy of user-provided phone data in your applications.
It's a integration of React International Phone library.
❗ Requirements
- Strapi v4
🔧 Installation
You just need to install the strapi-phone-validator
package via npm or yarn, at the root of your strapi project.
npm:
npm i strapi-phone-validator
yarn:
yarn add strapi-phone-validator
✨ Usage
Create a custom field for a phone number on content type builder page.
Now you can use Strapi Phone Validator as a custom field.
You can also validate a phone number also on creating a new entity via API endpoint:
<code>
import { factories, Strapi } from "@strapi/strapi";
import { PhoneNumberUtil } from 'google-libphonenumber';
const phoneUtil = PhoneNumberUtil.getInstance();
const isPhoneValid = (phone: string) => {
try {
return phoneUtil.isValidNumber(phoneUtil.parseAndKeepRawInput(phone));
} catch (error) {
return false;
}
};
export default factories.createCoreController(
"api::.......",
({ strapi }: { strapi: Strapi }) => ({
async create(ctx) {
const { data } = ctx.request.body;
const isValid = isPhoneValid(data.phone);
if(isValid) {
//...
}
...
},
})
);
<code>
To make Strapi Phone Validator work, you should take a look at the next section.
After restarting your Strapi app, Strapi Phone Validator should be listed as one of your plugins.
🚀 Strapi Configuration (required)
Allow Strapi Phone Validator assets to be loaded correctly by customizing the strapi::security middleware inside ./config/middlewares.js
.
Instead of:
export default [
// ...
'strapi::security',
// ...
];
Write:
export default [
// ...
{
name: "strapi::security",
config: {
contentSecurityPolicy: {
useDefaults: true,
directives: {
"connect-src": ["'self'", "https:"],
"script-src": ["https://cdnjs.cloudflare.com"],
"media-src": ["https://cdnjs.cloudflare.com"],
"img-src": ["https://cdnjs.cloudflare.com"],
},
},
},
},
// ...
];