Home > Software design >  Fluentvalidation 6.4.1.0 support me with Incorrect regex
Fluentvalidation 6.4.1.0 support me with Incorrect regex

Time:01-11

In my case, i want to validate for url image, some url is valid but result is wrong. Eg: link image is "https://fuvitech.online/wpcontent/uploads/2021/02/bta16600brg.jpg" or "https://fuvitech.online/wp-content/uploads/2021/02/bta16-600brg.jpg" reponse "The image link is not in the correct format".

My code here:

RuleFor(product => product.Images)
            .Length(1, 3000).WithMessage(Labels.importProduct_ExceedDescription, p => ImportHelpers.GetColumnName(typeof(ProductEntity).GetProperty(nameof(p.Images))))
            .Matches(@"^(http:\/\/|https:\/\/){1}?[a-z0-9] ([\-\.]{1}[a-z0-9] )*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$").WithMessage(Labels.importProduct_UrlNotCorrect, p => ImportHelpers.GetColumnName(typeof(ProductEntity).GetProperty(nameof(p.Images))));

Please help me where the above regex is wrong. Thank you.

CodePudding user response:

Try this:

NOTE the following regex pattern may trigger false positives and also may ignore valid image URLs, because it is very difficult to validate whether a given URL is valid.

^https?:\/\/(?:(?:[A-Za-z0-9] (?:-[A-Za-z0-9] ) |[A-Za-z0-9]{2,})\.) [A-Za-z]{2,}(?::\d )?\/(?:(?:[A-Za-z0-9] (?:(?:-[A-Za-z0-9] ) )?\/) |)[\w-] \.(?:jpg|jpeg|png)$

Explanation

  • ^ the start of a line/string.

  • https?:\/\/ match http with an optional letter s, followed by ://.

  • (?:(?:[A-Za-z0-9] (?:-[A-Za-z0-9] ) |[A-Za-z0-9]{2,})\.) This will match things like foo-foo.bar-bar., foo.bar-bar. and foo.

  • [A-Za-z]{2,} this will match the TLD part, e.g., com, org, this part with the previous part will match things like foo-foo.bar-bar.com, foo.bar-bar.com or foo.com.

  • (?::\d )? optional group of (a colon : followed by one or more digits) for port part.

  • \/(?:(?:[A-Za-z0-9] (?:(?:-[A-Za-z0-9] ) )?\/) |) this check for two things, the first one is /uploads/public-images/, /uploads/images/, the second one is a single /.

  • [\w-] this part for the file name, e.g., bta16-600brg.

  • \.(?:jpg|jpeg|png) you can add here multiple extensions, you can allow uppercase letters by using for example, [Jj][Pp][Gg] for jpg.

  • $ the end of the line/string.

See regex demo

CodePudding user response:

Thanks @SaSkY answer my question. I found my mistake. This source [.[a-z]{2,5}] only allows domain extensions from 2-5 characters. Example [.com] is valid. But in my case [.online] was not valid. I changed to [.[a-z]{1,10}].

  • Related