adonisjs / validator

Schema based validator for AdonisJS
MIT License
116 stars 39 forks source link

add `alphaNum` rule #148

Closed liaosankai closed 2 years ago

liaosankai commented 2 years ago

Proposed changes

add numeric allow for alpha rule

Types of changes

Checklist

thetutlage commented 2 years ago

Hey 👋

Thanks for the PR :). I think this should be its own rule alphaNum

liaosankai commented 2 years ago

It mean in the future there will be new schema types alphaNum in offical reference or I should use custom validation rules like this ?

node ace make:prldfile validator
// file: start/validator.ts
import { validator } from '@ioc:Adonis/Core/Validator'

const RULE_NAME = 'alphaNum'
const DEFAULT_MESSAGE = 'alphaNum validation failed'

validator.rule(RULE_NAME, (value, [ruleOptions], options) => {
  let charactersMatch = 'a-zA-Z0-9'

  if (ruleOptions['allow'].includes('space')) {
    charactersMatch += '\\s'
  }

  if (ruleOptions['allow'].includes('space')) {
    charactersMatch += '-'
  }

  if (ruleOptions['allow'].includes('underscore')) {
    charactersMatch += '_'
  }

  const pattern = `^[${charactersMatch}]+$`

  if (typeof value !== 'string') {
    return
  }

  if (!new RegExp(pattern).test(value)) {
    options.errorReporter.report(
      options.pointer,
      RULE_NAME,
      DEFAULT_MESSAGE,
      options.arrayExpressionPointer
    )
  }
})
// file: contracts/validator.ts
declare module '@ioc:Adonis/Core/Validator' {
  interface Rules {
    alphaNum(options?: { allow?: ('space' | 'underscore' | 'dash')[] }): Rule
  }
}
thetutlage commented 2 years ago

Just update the PR to have a alphaNum validation rule. The goal is to be it separate from the alpha rule, coz alpha-numeric is its own thing :)

liaosankai commented 2 years ago

@thetutlage Updated. :)

thetutlage commented 2 years ago

Hey sorry for the delay, was busy lately and now getting back to reviewing PRs :)

thetutlage commented 2 years ago

Thanks for the contribution 👍 . Really appreciate it

thetutlage commented 2 years ago

Can you please also open a PR for the documentation to document this rule? https://github.com/adonisjs/docs.adonisjs.com/