Indicative: how i can test regex?

I’m trying to validate a CPF document regex, i try this way:

const { validations } = use('indicative/validator')
const { validate } = use('Validator')

const rules = (values) => ({
   doc: 'string|required|max:11|min:11|regex:'+validations.regex([new RegExp(/([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g)]),
})

const messages = {
 regex: field => `${field} don't have the correct format`
}
class StudentController {

  async store ({ request, response }) {

    const estudante = { ...request.all(), user_id: request.user_id }

    const validation = await validate(estudante, rules(rules), messages)

    if (validation.fails()) {

      return response.validateError(validation)

    }
}

But when i try to do a post with the doc with value:
39257443828

I receive a response error with:

doc don’t have the correct format

What i’m doing wrong? i test this regex in regex testers sites and this value pass.

Also tried:

doc: 'string|required|max:11|min:11|regex: ([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g'

I also tried without the /g

Also tried:

doc: 'string|required|max:11|min:11|regex:'+new RegExp('([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})'),

1 Like

^ it’s recommended to use rule()

Try this:

const { validate, rule } = use("Validator");

const rules = {
      doc: [
        rule(
          "regex",
          /([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g
        )
      ]
    };
2 Likes

Thanks, this works.

My final code is:

doc: [rule("regex", /([0-9]{2}[\.]?[0-9]{3}[\.]?[0-9]{3}[\/]?[0-9]{4}[-]?[0-9]{2})|([0-9]{3}[\.]?[0-9]{3}[\.]?[0-9]{3}[-]?[0-9]{2})/g),

      rule("required"),

      rule("min", 11),

      rule("max", 11),

      rule("string")],
1 Like

ohhh no
why is it so important?