0

I have the following field which should accept a YouTube Video ID, I am trying to prevent full URI from being used but cannot seem to find the appropriate use case in Joi Documentation.

youtubeVideoId: Joi.string()
    .label('YouTube Video ID')
    .allow(null)
    .allow('')
    .invalid('http', 'www'),

I thought the above would work however invalid looks at the string as a whole not contains.

I also tried using but this does not work.

youtubeVideoId: Joi.string()
    .label('YouTube Video ID')
    .allow(null)
    .allow('')
    .invalid(Joi.string().uri()),

Can anyone provide a Joi validation to prevent a URI from being accepted?

James
  • 281
  • 3
  • 9

2 Answers2

0

You can use .regex to validate your string.

A youtube video ID is composed by a string with 11 characters, eg: dQw4w9WgXcQ

Your regex expression could be this: /^([A-Za-z0-9_\-]{11})$/

This is how your Joi validation will look like:

Joi.object({
    youtubeId: Joi.string().regex(new RegExp(/^([A-Za-z0-9_\-]{11})$/)).required()
})

You can find more details about the regex here and test it on regex101.com.

soltex
  • 2,993
  • 1
  • 18
  • 29
0

I ended up using .max(11) as suggested by @ankh as this fits the purpose.

James
  • 281
  • 3
  • 9