2

I am using Adonis.js in the latest version but cannot validate... Already tried

request.multipart.file('avatar', {
  types: ['jpeg', 'jpg', 'png'], // I already tried -> type: ['image'] types: ['image'],
  size: "4mb"
  }, async file => {
    await Drive.put(key, file.stream)
})

.../Validators/changeAvatar.js

'use strict'

class UserChangeAvatar {
  get rules() {
    return {
      avatar: 'required|file|file_ext:png,jpg,jpeg,svg'
    }
  }
}

module.exports = UserChangeAvatar

Nothing works, the code lets you upload any type of file, like .pdf or .mp4

There's nothing in the Adonis.js documentation talking about it either.

Package version

Version 4.1 "@adonisjs/framework": "^5.0.9"

Node.js and npm version

NODE - v10.15.0 NPM - 6.10.1

Ahmad Faiyaz
  • 316
  • 4
  • 16
Yung Silva
  • 1,324
  • 4
  • 20
  • 40

1 Answers1

4

The validation rules do not work for the multipart file upload on adonis. You need to do manual validation. For example:

// Helper function
function fileStreamValidation(file, validationRules) {
  const validationErrors = []
  if (!RegExp(/^[0-9a-zA-Z_\-.]+$/).test(file._clientName)) {
    validationErrors.push(
      `${file._clientName}'s name should only contain alphanumeric, underscore, dot, hypen`
    )
  }
  if (validationRules.extnames && validationRules.extnames.length) {
    const [_, fileExtension] = file._clientName.split(/\.(?=[^.]+$)/)
    if (!validationRules.extnames.includes(fileExtension)) {
      validationErrors.push(`${file._clientName}'s extension is not acceptable`)
    }
  }
  if (validationRules.maxFileSizeInMb) {
    if (file.stream.byteCount > validationRules.maxFileSizeInMb * 1000000) {
      validationErrors.push(`${file._clientName}'s size exceeded limit`)
    }
  }
  return validationErrors
}

/* validation in controller */
const validationOptions = {
  extnames: ['in', 'out'],
  maxFileSizeInMb: parseInt(Env.get('MAX_FILE_SIZE_IN_MB'))
}
request.multipart.file('datasets[]', {}, async file => {
  const errors = fileStreamValidation(file, validationOptions)
})
Ahmad Faiyaz
  • 316
  • 4
  • 16