Tigt
Tigt

Reputation: 1487

How do I use an <input>'s pattern attribute to require at least one usable character?

I've got an <input> searchbox, and I want to add pattern to guide the user to submitting more than just whitespace. The required attribute doesn't let them submit an empty string, but searching for a couple of spaces goes through and isn't useful.

I've tried the following, but input such as "a couple of keywords" isn't valid with them:

I know the ^ and $ symbols are implied, and adding them doesn't change anything in the results.

How do I write a pattern that matches every input except white space without any other characters?

Upvotes: 1

Views: 2689

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You could try the below regexes.

pattern = ".*\S.*"

or

pattern = ".*[^ ].*" 

So this regex asserts that there must be atleast one non-space character present in the input string. .* matches any character zero or more times. [^ ] negated character class which matches any character but not of a space. Since [^ ] matches also a tab character, adding also the tab character [^ \t] inside the char class would be better.

Upvotes: 3

Related Questions