Pattern validator is invalid for IP address regex

前端 未结 1 1194
南旧
南旧 2021-01-23 15:59

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/         


        
相关标签:
1条回答
  • 2021-01-23 17:01

    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.

    0 讨论(0)
提交回复
热议问题