validate.js
validate.js copied to clipboard
Validator doesn't work properly
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
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/
@wzup Did you get it resolved?
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
}