Reputation: 20
I've only just started working with pattern
and would like to know how I can validate an <input type="text" />
to only accept the value if there is also a space in the value?
Upvotes: 0
Views: 2641
Reputation: 29645
The answer will depend on what you consider a space: do you refer to a white space? a tab? a new line? all of the above?
If what you want to match is only the white space (like when you press the space bar), you could use an expression like .*[ ].*
:
.*
means any character 0 or more times.[ ]
means a blank space.Here is a demo:
<form method="post" action="javascript:void(0)">
<input type="text" value="" pattern=".*[ ].*" required />
<br/>
<input type="submit" value="send" />
</form>
If what you want to match is any whitespace (space bar, new line, tab, etc.), use \s
. But notice that the characters matched by it may depend on the regex flavor (source).
In that case, the code would be like this:
<form method="post" action="javascript:void(0)">
<input type="text" value="" pattern=".*[\s].*" required />
<br/>
<input type="submit" value="send" />
</form>
Upvotes: 1