validate.js icon indicating copy to clipboard operation
validate.js copied to clipboard

Validator doesn't work properly

Open wzup opened this issue 6 years ago • 3 comments

Here is an example. Why? When I remove g flag, it works properly. Why?

let constraint = {
    "mobile": {
        "presence": true,
        "format": {
            "pattern": /^\+?[\d-\s.]{5,}$/ig,
            "message": "^Valid phone number required"
        }
    }
}

// One time - OK
validate({'mobile': '+44444'}, m);
> undefined

// Very next time - Error
validate({'mobile': '+44444'}, m);
> {
  "mobile": [
    "Valid phone number required"
  ]
}

// OK again
validate({'mobile': '+44444'}, m);
> undefined

... so forth

wzup avatar Jun 19 '18 16:06 wzup

Not sure if you intended to validate using variable m as your constraints. Changed to the name of your constraint and it passes validation every time there is valid input and fails when the input is not valid.

Related jsfiddle: https://jsfiddle.net/mapntL7k/8/

kylef000 avatar Sep 18 '18 20:09 kylef000

@wzup Did you get it resolved?

mrgurdeep avatar Sep 16 '19 14:09 mrgurdeep

It happens because JavaScript saves regex runs iterator at every regexp.exec() function call and if you have been tested all string it returns null. It was solved by writing custom validator with code below that creates new regex instance.

validateJS.validators.regEx = function (value: any, options: IValidateRegExOptions) {
  const { pattern, message } = options
  const outputMessage = message || 'has an incorrect format'

  if (value) {
    const stringValue = String(value)
    const newRegExpInstance = new RegExp(pattern)

    if (newRegExpInstance.exec(stringValue)) {
      return null
    }
  }

  return outputMessage
}

amabunny avatar Nov 20 '19 17:11 amabunny