Playing Next Lesson In
seconds

Let's Learn AdonisJS 6 #3.8

Form Basics and CSRF Protection

In This Lesson

We'll cover the basics of working with HTML forms in AdonisJS and how they incorporate Cross-Site Request Forgery (CSRF) protection via AdonisJS Shield.

Created by
@tomgobich
Published

Join the Discussion 5 comments

Create a free account to join in on the discussion
  1. @frp

    Are you going to do anything with form validation? I'm trying to write a custom rule for Vine and the docs don't seem to say what the function should return. In Laravel a validation function returned true or false but I cannot figure it out from the example they use in the Vine docs.

    1
    1. Responding to frp
      @tomgobich

      Yeah, validation will come with module 7, which focuses on form flow. The database modules are the last large modules, so things should start flowing quickly thereafter :)

      Anything that doesn't report an error is considered valid. So, to walk through the example within Vine's documentation:

      import { FieldContext } from '@vinejs/vine/types'
      
      /**
       * Options accepted by the unique rule
       */
      type Options = {
        table: string
        column: string
      }
      
      /**
       * Implementation
       */
      async function unique(
        value: unknown,
        options: Options,
        field: FieldContext
      ) {
        /**
         * 1. If the value isn't a valid string, we'll bail out here
         * The "string" rule will handle this particular validation
         * vine.string().use(unique({...}))
         */
        if (typeof value !== 'string') {
          return
        }
        
        // 2. Otherwise, we'll continue validating uniqueness by checking the db
        const row = await db
         .select(options.column)
         .from(options.table)
         .where(options.column, value)
         .first()
         
        // 3. If value is NOT unique, we'll report the error
        if (row) {
          field.report(
            'The {{ field }} field is not unique',
            'unique',
            field
          )
        }
      
        // If no error was reported by the end of the method
        // we'll assume everything was valid
      }
      
      export const uniqueRule = vine.createRule(unique)
      
      Copied!
      0
      1. Responding to tomgobich
        @frp

        Ok, so the return earlier is just passing on to the next validator, and unless you have that field.report() method, you are good. Thanks, that makes sense.

        1
        1. Responding to frp
          @tomgobich

          Yep, exactly!! :) Anytime!!

          0
  2. @nocturna

    almost..

    0