Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support encoding uri #3027

Merged
merged 9 commits into from
Apr 23, 2024
6 changes: 6 additions & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,12 @@ declare namespace Joi {
* Validate the domain component using the options specified in `string.domain()`.
*/
domain?: DomainOptions;
/**
* Encode URI before validation.
*
* @default false
*/
encodeUri?: boolean;
}

interface DataUriOptions {
Expand Down
6 changes: 5 additions & 1 deletion lib/types/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ module.exports = Any.extend({
uri: {
method(options = {}) {

Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme']);
Common.assertOptions(options, ['allowRelative', 'allowQuerySquareBrackets', 'domain', 'relativeOnly', 'scheme', 'encodeUri']);

if (options.domain) {
Common.assertOptions(options.domain, ['allowFullyQualified', 'allowUnicode', 'maxDomainSegments', 'minDomainSegments', 'tlds']);
Expand All @@ -665,6 +665,10 @@ module.exports = Any.extend({
return helpers.error('string.uri');
}

if (helpers.prefs.convert && options.encodeUri) {
value = encodeURI(value);
HYOSITIVE marked this conversation as resolved.
Show resolved Hide resolved
}

const match = regex.exec(value);
if (match) {
const matched = match[1] || match[2];
Expand Down
9 changes: 9 additions & 0 deletions test/types/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -9012,6 +9012,15 @@ describe('string', () => {
]);
});

it('validates uri after encoding', () => {

const schema = Joi.string().uri({ encodeUri: true });

Helper.validate(schema, { convert: true }, [
['https://linkedin.com/in/aïssa/', true, 'https://linkedin.com/in/a%C3%AFssa/']
]);
});

it('errors on unknown options', () => {

expect(() => Joi.string().uri({ foo: 'bar', baz: 'qux' })).to.throw('Options contain unknown keys: foo,baz');
Expand Down
Loading