Custom valid URL validation using regex in Javascript

Here

I am checking the URL with the following line, which should be either http / https or the ip address along with the request line and another bracket of square brackets [].

I want to prevent the following URL bracket

2) http://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192 ? [publisher[client_id]Id] - Not Allowed

What should be a regular expression to prevent [publisher[client_id]Id] sting?

I use the following regex for the above lines

 var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/; if(!regex .test(str)) { return false; } else { return true; } 

What needs to be changed for this code?

Please help me for the same.

+5
source share
2 answers

Try the following:

 var strings = [ '[publisher[client_id]Id]', '[publisher_id]' ]; var pattern = /\[.*\[.*\].*\]/; strings.forEach(function(string){ if(pattern.test(string)) { console.log(string + " -> matched"); } else { console.log(string + " -> not matched"); } }); 
0
source

try it. the first group returns url without parameter (with our publisher, etc.)

Sorry, did not read it carefully. try this and return true if valid

edited

 var t1 = "htts:/192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]"; var t2 = "https://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192"; var t3 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]"; var t4 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?name=[publisher[client_id]]"; var t5 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?foo=bar&name=[publisher[client_id]]"; function check(str) { var url = /((http[s]?:\/\/){1,1}(\w+[-.\/]{0,1}\w?)*)/g, p = /([\?\&](\w+=){0,1}\[\w+\[\w+\]\w*\])/g; /*check for url*/ if (!url.test(str)) { return "invalid url"; } /*check for [userid[userid]]*/ return p.test(str) ? "invalid" : "valid"; } document.body.innerHTML = check(t1) + "</br>"; document.body.innerHTML += check(t2) + "</br>"; document.body.innerHTML += check(t3) + "</br>"; document.body.innerHTML += check(t4) + "</br>"; document.body.innerHTML += check(t5) + "</br>"; 

considers

0
source

Source: https://habr.com/ru/post/1259491/


All Articles