From bb5fd368275da1c51d4320f92c9b73e42be8d9be Mon Sep 17 00:00:00 2001 From: Jonathan Thom Date: Thu, 21 Nov 2019 21:26:59 -0800 Subject: [PATCH] Improves accuracy of datauri regex Fixes Or Enhances https://github.com/go-playground/validator/issues/518. Make sure that you've checked the boxes below before you submit PR: [x] Tests exist or have been written that cover this particular change. Change Details: The datauri validation was not allowing certain valid strings; this commit updates the regex to meet RFC 2397. I drew heavily on this gist https://gist.github.com/khanzadimahdi/bab8a3416bdb764b9eda5b38b35735b8, but had to make a few updates to remove some negative lookaheads (which Go doesn't allow afaik), and to account for the way the `isDataURI` function works - it validates the base64 separately from the other parts of the uri. @go-playground/admins --- regexes.go | 2 +- validator_test.go | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/regexes.go b/regexes.go index 0253d70..7161804 100644 --- a/regexes.go +++ b/regexes.go @@ -31,7 +31,7 @@ const ( aSCIIRegexString = "^[\x00-\x7F]*$" printableASCIIRegexString = "^[\x20-\x7E]*$" multibyteRegexString = "[^\x00-\x7F]" - dataURIRegexString = "^data:.+\\/(.+);base64$" + dataURIRegexString = `^data:((?:\w+\/(?:([^;]|;[^;]).)+)?)` latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$` diff --git a/validator_test.go b/validator_test.go index d74247f..46fa02c 100644 --- a/validator_test.go +++ b/validator_test.go @@ -3435,12 +3435,15 @@ func TestDataURIValidation(t *testing.T) { {"data:image/png;base64,12345", false}, {"", false}, {"data:text,:;base85,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false}, + {"data:image/jpeg;key=value;base64,UEsDBBQAAAAI", true}, + {"data:image/jpeg;key=value,UEsDBBQAAAAI", true}, + {"data:;base64;sdfgsdfgsdfasdfa=s,UEsDBBQAAAAI", true}, + {"data:,UEsDBBQAAAAI", true}, } validate := New() for i, test := range tests { - errs := validate.Var(test.param, "datauri") if test.expected {