danoseun
danoseun

Reputation: 69

Importing from validator in javascript

I want to use the validator for an express project. How do I import just two subsets of the packages directly?

Like:

import {isEmail, isEmpty} from 'validator';

or importing each on a separate line.

I just want to know if there is another option apart from import validator from 'validator'; as stated on the https://www.npmjs.com/package/validator

Upvotes: 0

Views: 4193

Answers (2)

yBrodsky
yBrodsky

Reputation: 5041

const isEmailValidator = require('validator').isEmail;
const isEmptyValidator = require('validator').isEmpty;


isEmailValidator('[email protected]');

Like this you mean? What you wrote should also be valid:

import {isEmail, isEmpty} from 'validator';

isEmail('[email protected]');

Edit for clarification: As you can see here https://github.com/chriso/validator.js/blob/master/src/index.js the library is exporting an object with each function. You can import everything import validator from 'validator' or you can use destructuring to get only a few properties.

Upvotes: 1

zero298
zero298

Reputation: 26878

const {isEmail, isEmpty} = require('validator');

This will not actually stop node from importing all of validator though. This just has node load the validator object that is returned from that modules export and then destructures isEmail and isEmpty out of the exported Object.

Maybe whenever ES6 modules become full supported you can use the regular import syntax. See node.js documentation: ECMAScript Modules.

Upvotes: 0

Related Questions