WP
36 0
Asked
Updated
Viewed
9.2k 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

2 Answers

  • Votes
  • Oldest
  • Latest
WP
36 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
Answered
Updated

You can use the JavaScript trim() method to remove any leading or trailing white spaces from the input before validating it against your regular expressions.

For example, you can update your validation code to something like this:

inputValue = inputValue.trim();
if(inputValue.match(pattern)) {
    // input is valid
} else {
    // input is not valid
}

This will ensure that any leading or trailing white spaces are removed before the input is matched against the regular expression, and it should solve the issue you're experiencing with copied input containing white spaces.

  • 0
    While this is a potential solution to the problem; before he was not having to utilize Javascript at all. Additionally, the question was specifically about the HTML pattern attribute. I would much prefer a solution that involves using zero Javascript if such a solution exists, which in this case it does. If however, this input is already having to go through some sort of JavaScript validation, then it might not be much more to add in the code to trim the value first. — Brian Wozeniak
add a comment
-1