Codementor Events

How to Create a Custom Validator in AdonisJS

Published Jul 18, 2023
How to Create a Custom Validator in AdonisJS

In this blog post, we will show you how to create a custom validator in AdonisJS. We will use a sample rule that checks for the maximum length of a number.

First, we need to create a new file called validator.ts in the start directory. In this file, we will define our custom validator function.

function snakeToSentence(field) {
    return field
      .replace(/_./g, function (match) {
        return ' ' + match.charAt(1).toUpperCase()
      })
      .replace(/^./, function (firstLetter) {
        return firstLetter.toUpperCase()
      })
  }

validator.rule('maxLengthRule', (value, __, { errorReporter, field }) => {
  const sentenceCase = snakeToSentence(field)
  if (value.toLocaleString('fullwide', { useGrouping: false }).length > 10) {
    errorReporter.report(
      sentenceCase,
      'maxLengthRule',
      `${sentenceCase} should have a maximum of 10 digits.`
    )
  }
})

This function takes three arguments:

  • value: The value that is being validated.

  • __: A placeholder for any additional arguments that may be passed to the validator.

  • errorReporter: An object that can be used to report errors.

The function first converts the field name to a sentence case using the snakeToSentence function. Then, it checks if the length of the value is greater than 10. If it is, then the function reports an error.

Next, we need to export our custom validator function. We can do this by adding the following code to the contracts/validator.ts file:

declare module '@ioc:Adonis/Core/Validator' { interface Rules {
        maxLengthRule(): Rule
    }
}

Finally, we can use our custom validator in our validation schema. For example, the following code validates the sell_price field to ensure that it is a number with a maximum length of 10 digits:

return { 
   sell_price: schema.number([rules.unsigned(), rules.maxLengthRule()]),
}

That's it! We have now created a custom validator in AdonisJS.

I hope this helps! Let me know if you have other questions.

NEED HELP? Hire me on Code Mentor or talk to our experts at https://ghanshyamdigital.com/

Discover and read more posts from Shyam Makwana
get started
post commentsBe the first to share your opinion
AS freelancing
9 months ago

Make a Form Group, design a custom validator function, add an error message to your form, and so forth.
Try Out Your Validator.
I utilize 10 RxJS operators on a daily basis when developing Angular.
https://zachbryanmerchandise.shop/

Show more replies