Javascript hostname and ip validate
Validating hostname and IP occurs pretty often.
This is what I use for a field that can contain both IPV4 or hostname :
if (value.length === 0 || value.length > 511)
{ return "Address length must be between 1 and 511 characters.";
}
var regExpIp = new RegExp("^(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]?)$");
var regResultIp = regExpIp.exec(value);
var regExpHostname = new RegExp(/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/); // RFC 1123
var regResultHostname = regExpHostname.exec(value);
if (regResultIp === null && regResultHostname === null)
{ return "Address must be a valid IP address or hostname.";
}
Note: Be careful, new RegExp("") and new RegExp(//) do not behave the same! The first one requires double escaping such as \\. while the second form only require one backslash to escape special characters. Read more Javascript errors not to do here.
Recent Comments