0

i'm trying to use HTML5 Pattern in React. My input code:

<input type="text" pattern="[a-zA-Z]" />

I want something like this: Pizza Texas or Spaghetti Bolognese. So i need pattern for strings with space between. But it would be good if pattern allows for 3 or more strings.

jhpratt
  • 6,841
  • 16
  • 40
  • 50
xyztest
  • 17
  • 7
  • So you want to match a number of occurrences of ``? What have you tried, how did your attempt(s) fail? – David Thomas Jul 20 '19 at 11:44
  • Try this `pattern="[a-zA-Z ]"` – ravibagul91 Jul 20 '19 at 11:47
  • I'm tried with pattern="[a-zA-Z][a-zA-Z]" and pattern="[a-zA-Z]{2}", but this didn't work. – xyztest Jul 20 '19 at 11:52
  • You are not adding space, see my comment. – ravibagul91 Jul 20 '19 at 11:55
  • pattern="[a-zA-Z ]" didn't work at all, "Pizza" "Pizza Texas" etc. – xyztest Jul 20 '19 at 11:57
  • Note that you've not used any white-space characters in either of those examples, which you'd need to add for this. Would this be what you're looking for: [demo](https://jsfiddle.net/davidThomas/o4hnwsc2/1/)? If so, then you're looking to use `` which is taken from this answer: https://stackoverflow.com/a/15473717/82548 (which, in turn, makes this question a duplicate of that one). – David Thomas Jul 20 '19 at 12:00
  • Its pretty good, but i want only strings, in your demo i can write numbers – xyztest Jul 20 '19 at 12:04
  • You can try this `[a-zA-Z ?]*` notice the space and question mark. – ravibagul91 Jul 20 '19 at 12:17
  • If you don't want to allow multiple spaces and also not at the start or end, you could use `[a-zA-Z]+(?: [a-zA-Z]+)*` See https://regex101.com/r/D89hI9/1 Note that adding the question mark in the character class would allow you to match it as a character. – The fourth bird Jul 20 '19 at 14:41

1 Answers1

0

This represents one word:

([a-zA-Z]+)

This represents one word followed by a single space:

([a-zA-Z]+\s)

This represents two or more:

{2,}

All together:

([a-zA-Z]+\s){2,}([a-zA-Z]+)

Two or more words followed by a single space then ending in a word.

Note: If you want a minimum of two words then change {2,} to {1,}.

In the demo if only 1 or 2 words are entered then submitted there should be an error popup. If 3 or more words are entered and then submitted, the whole form should disappear.

<form>
  <input name='threeWords' type='text' pattern='([a-zA-Z]+\s){2,}([a-zA-Z]+)' required>
  <input type='submit'>
</form>
zer00ne
  • 41,936
  • 6
  • 41
  • 68