-2

i need to find a way to guide user to filling a string field. I need to oblige user to populate field this in this way :

IP ADRESS (SPACE) PORT (end)

IP ADRESS (SPACE) PORT (end)

For example :

123.45.70.2 8080

143.23.10.10 433

I need to have a list with ip adress and associated port.

I read something abuot RegEx , but i can't find a way to do it.

The field that i want to control is a Multiline Text variable of an item of Service Catalog.

Can anyone help me?

Thanks.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Hi, welcome to Stack Overflow. I'm not sure I understand your requirements completely - is it a multiline text where each line should be exactly of the format mentioned above? How strict do you want to be when verifying the format (range validation, for example)? Only IPv4 addresses? You'll find plenty of regexes for that here... – Tim Pietzcker Oct 03 '19 at 12:37
  • why not use input mask plugin https://github.com/RobinHerbots/Inputmask – Muhammad Omer Aslam Oct 03 '19 at 12:53

2 Answers2

5

You can use code below to extract all ip address in a given string using javascript:

function findAll(regexPattern, sourceString) {
    let output = []
    let match
    // make sure the pattern has the global flag
    let regexPatternWithGlobal = RegExp(regexPattern,"g")
    while (match = regexPatternWithGlobal.exec(sourceString)) {
        // get rid of the string copy
        delete match.input
        // store the match data
        output.push(match[0].replace(":", " "))
    } 
    return output
}


var str = "123.23.255.123:1233 128.9.88.77:1233"; 
var ipAddress = findAll("(([0-1]?[0-9]?[0-9]|[2]?[0-5][0-5])\.){3}([0-1]?[0-9][0-9]|[2]?[0-5][0-5])\:[0-9]{4}", str);

RegExp(str, "g")
console.log(ipAddress)

the output of above code will be

[ '123.23.255.123 1233', '128.9.88.77 1233' ]
Waqas Javed
  • 424
  • 2
  • 11
1

Regex could be used there but you have to be very careful about edge cases.

This sample solves your problem of multiline string that should contain only IPv4 addresses followed by port after space.

eg.

123.45.70.2 8080
143.23.10.10 433

And the JS code sample

var textInput= `
123.45.70.2 8080
143.23.10.10 433
`.trim();

var isValid = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3} [1-9][0-9]*$/mg.test(textInput);
console.log(isValid);
wirher
  • 916
  • 1
  • 8
  • 26