Validate IP address

saurabhsharma
Giga Contributor

Hi

I have to validate IP address and format should be like this 123.23.23.34

how can I validate it by using RegEx.

Thanks

Saurabh

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Saurabh,

Following you can use and it works.

function validateIP(ip) {
//Check Format
var ip = ip.split(".");

if (ip.length != 4) {
return false;
}

//Check Numbers
for (var c = 0; c < 4; c++) {
//Perform Test
if ( ip[c] <= -1 || ip[c] > 255 ||
isNaN(parseFloat(ip[c])) ||
!isFinite(ip[c]) ||
ip[c].indexOf(" ") !== -1 ) {

return false;
}
}
return true;
}

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

6 REPLIES 6

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Saurabh,

Following you can use and it works.

function validateIP(ip) {
//Check Format
var ip = ip.split(".");

if (ip.length != 4) {
return false;
}

//Check Numbers
for (var c = 0; c < 4; c++) {
//Perform Test
if ( ip[c] <= -1 || ip[c] > 255 ||
isNaN(parseFloat(ip[c])) ||
!isFinite(ip[c]) ||
ip[c].indexOf(" ") !== -1 ) {

return false;
}
}
return true;
}

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

where do we have to put this code.

Prateek kumar
Mega Sage

This works for me. Try this:

var pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;


if(!pattern.test(newValue) || (newValue.length<3) ){
alert("You have entered an invalid IP address!") ;
g_form.setValue('u_ip_address', '');
}
}

 

Source:https://www.w3resource.com/javascript/form/ip-address-validation.php


Please mark my response as correct and helpful if it helped solved your question.
-Thanks

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Saurabh,

Any update on this?
Can you mark my answer as correct, helpful if you were able to achieve the requirement. This helps in removing this question from unanswered list and helps users to learn from your thread. Thanks in advance.

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader