WP
29 0
Asked
Updated
Viewed
4.6k times

I have a form that can give information on a domain name (not subdomains) and on IP addresses.

When the user enters the domain name or IP address into the appropriate form input box, I validate it to see if it is of the correct format.

For domain name I use:

pattern="^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$"

For IP Address I use (IPV4):

pattern="((^|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}$"

They both work properly if the user enters the information directly into the form with their keyboard. However, if the user copies the domain or IP address and happens to copy a white space before and after the information, and pastes it into the input box, the form displays a format error. If I remove the beginning and ending space it works fine.

How can you ignore the beginning and ending white spaces so that the format becomes valid?

add a comment
1

1 Answer

  • Votes
  • Oldest
  • Latest
WP
29 0
Answered
Updated

By luck I managed to find the syntax. Use \s* to account for any white spaces.

With that said for the domain pattern validation I now use:

pattern="^\s*([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}\s*$"

For IP Address I now use (IPV4):

pattern="((^\s*|\.)((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]?\d))){4}\s*$"

For the IP address I had to put it inside the anchors ^ and $ or else it did not work. Now, with this updated pattern it does not matter how many white spaces are at the beginning or at the end, it will only validate what is important here between those spaces.

add a comment
1