Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question @Matches decorator with my regex shows true sometimes while false sometimes #484

Closed
rubiin opened this issue Dec 6, 2019 · 17 comments
Labels
status: invalid / expired Issues with no action to take. type: question Questions about the usage of the library.

Comments

@rubiin
Copy link
Contributor

rubiin commented Dec 6, 2019

I am using class-validator with nestjs. I have a password field like this:

  @Matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).{6,64}$/gm, {
    message:
      'Password must be between 6 and 64 characters long with 1 special character and capital character each',
  })

but sometimes the password passes this while sometimes it doesnt

@rubiin
Copy link
Contributor Author

rubiin commented Dec 6, 2019

@vlapo also when is the release of next version. I like to use the uuid fix

@yardenshoham
Copy link

yardenshoham commented Dec 23, 2019

I've also encountered this with @Matches.

Here's my user class:

import {
  IsEmail,
  Matches,
  IsOptional,
  IsPhoneNumber,
  IsDefined,
  validateSync
} from "class-validator";

export class User {
  @IsDefined()
  @IsEmail()
  public email: string;

  @IsDefined()
  @Matches(/[a-zA-Z0-9_-]{2,20}/)
  public username: string;

  @IsDefined()
  @Matches(/^\$2[ayb]\$[\d]{2}\$[./A-Za-z0-9]{53}$/)
  private _password: string;

  @IsOptional()
  @IsPhoneNumber(null)
  public phoneNumber?: string;

  constructor(
    email: string,
    username: string,
    password: string,
    phoneNumber?: string
  ) {
    this.email = email;
    this.username = username;
    this.password = password;
    if (phoneNumber) {
      this.phoneNumber = phoneNumber;
    }
  }
}

The test I've run:

console.log(
  validateSync(
    new User(
      "test.user@test.domain.com",
      "I'm way too long to be a username, much too long",
      "$2y$12$E6I8o3kUs8CsSs0WnyYiGOmBeVxfhvaEbxPGgJ334jfpB//gEwFYO"
    )
  )
);

This yields no errors: []

EDIT: My RegEx was wrong. Adding ^ at the beginning and $ at the end fixed it.

@insanebaba
Copy link

insanebaba commented Jan 1, 2020

Same here

I'm trying to use class validator for validating my inputtype in type-graphql but the @matches decorator, is not working, All other decorators with suffix 'Is' are working, but not this one.

``

const mobileNumberRegex = /^(\+[0-9]{1,3}[- ]?)?[0-9]{9,10}$/;

@Field()
@Matches(mobileNumberRegex)
mobileNumber!: string;

``
I'm expecting error when the mobile number is not matching, but it's not there. Validate method also doesn't pass as expected

@yardenshoham
Copy link

yardenshoham commented Jan 1, 2020

@insanebaba

Same here

I'm trying to use class validator for validating my inputtype in type-graphql but the @matches decorator, is not working, All other decorators with suffix 'Is' are working, but not this one.

``

const mobileNumberRegex = /^(\+[0-9]{1,3}[- ]?)?[0-9]{9,10}$/;

@Field()
@Matches(mobileNumberRegex)
mobileNumber!: string;

``
I'm expecting error when the mobile number is not matching, but it's not there. Validate method also doesn't pass as expected

For your use case I'd recommend the @IsPhoneNumber(null) decorator.

@insanebaba
Copy link

@insanebaba

Same here
I'm trying to use class validator for validating my inputtype in type-graphql but the @matches decorator, is not working, All other decorators with suffix 'Is' are working, but not this one.
``

const mobileNumberRegex = /^(\+[0-9]{1,3}[- ]?)?[0-9]{9,10}$/;

@Field()
@Matches(mobileNumberRegex)
mobileNumber!: string;

``
I'm expecting error when the mobile number is not matching, but it's not there. Validate method also doesn't pass as expected

For your use case I'd recommend the @IsPhoneNumber(null) decorator.

Thanks for suggestion, @IsPhoneNumber(null) works, but I want to have more control over the pattern.

I solved my issue by stepping down to version 0.10.2

Thank you everyone, I hope this issue gets addressed in later versions.

@rubiin
Copy link
Contributor Author

rubiin commented Jan 23, 2020

@vlapo do you know how can i resolve this

@yardenshoham
Copy link

@rubiin Please provide an example of an input that fails.

@windok
Copy link

windok commented Feb 28, 2020

Facing the same issue with class-validator package version 0.11.0

import {  IsArray,  IsOptional,  Matches } from 'class-validator';

export class MyDto {
  @IsArray()
  @IsOptional()
  @Matches( /^[\w .,-]+$/gi, { each: true })
  readonly rangeFilters?: string[];
}

values that pass only each second time: price, price.amountToPay,500,600

        {
            "target": {
                "rangeFilters": [
                    "price.amountToPay,500,600"
                ]
            },
            "value": [
                "price.amountToPay,500,600"
            ],
            "property": "rangeFilters",
            "children": [],
            "constraints": {
                "matches": "each value in rangeFilters must match /^[\\w .,-]+$/gi regular expression"
            }
        }

@aozisik
Copy link

aozisik commented Mar 6, 2020

@windok , @rubiin
Please read the following thread on the use of g flag.
It makes the regex object stateful, which explains this bug.

I guess you'll have to avoid that flag to fix the issue.

https://stackoverflow.com/questions/6739136/consecutive-calls-to-regexp-test-fail-for-pattern-with-global-option

@vlapo
Copy link
Contributor

vlapo commented Mar 16, 2020

@rubiin Did you resolve your issue?

@DUDY206
Copy link

DUDY206 commented Sep 15, 2021

I have the same problem

@IsString()
 @MinLength(8)
 @MaxLength(20)
 @Matches(/((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-z0-9@$!%*?&]+)+/g)
 password: string;

response sometime true, sometime false with same request

@kazemimorteza68
Copy link

kazemimorteza68 commented Jan 22, 2022

I have the same problem

@IsString()
 @MinLength(8)
 @MaxLength(20)
 @Matches(/((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-z0-9@$!%*?&]+)+/g)
 password: string;

@matches('^09[0-9]{9}',"",{"message":"phone is incorrect"})
phone: string;

after regex pattern we need pass empty string and third argument be our message

@bezenson
Copy link

Hm, issue opened from 2019. Got the same issue.

wtf.mp4

IMAGE 2022-06-20 20:03:58

I fixed it by removing /g flag from regular expression

@ibrahimwithi
Copy link

Got the same issue I want to validate time format '/^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$/' but it fails on 08:30

@lublot
Copy link

lublot commented Nov 11, 2022

Hm, issue opened from 2019. Got the same issue.

wtf.mp4
IMAGE 2022-06-20 20:03:58

I fixed it by removing /g flag from regular expression

Thank you! It worked for me.

@NoNameProvided NoNameProvided added type: question Questions about the usage of the library. status: invalid / expired Issues with no action to take. labels Dec 9, 2022
@NoNameProvided
Copy link
Member

As @aozisik explained correctly this is how the g flag works with Regexes. From MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test:

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).

Closing this as there is no action to take from our side.

@NoNameProvided NoNameProvided changed the title @matches with my regex shows true sometimes while false sometimes question @Matches decorator with my regex shows true sometimes while false sometimes Dec 16, 2022
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jan 16, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
status: invalid / expired Issues with no action to take. type: question Questions about the usage of the library.
Development

No branches or pull requests