I\'m using the following regex to validate IP address pattern:
/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/
Since you are using Validators.pattern
, you do not need to anchor the pattern manually (no need for word boundaries, angular will enclose the whole pattern with ^
and $
automatically) and you need to define it properly with a string literal doubling the escaping backslashes, else they will be removed by JS.
Use
const ipPattern =
"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
You may add ^
at the start and $
at the end just in case you want to keep the pattern explicit (it does not do any harm to have two ^
at the pattern start and $$
at the end, just the engine will check the start/end of the string positions twice).
NOTE: if you have more complex patterns with alternations, it is a good idea to use ^
and $
explicitly in those patterns since angular automatic anchoring does not enclose the whole pattern with an optional non-capturing group, it just appends ^
and $
to the provided pattern.