2

I need to combine these 2 patterns together or use them both in my <input> field

I have pattern matching to check for a valid time - which works great and the field is "NOT REQUIRED" so we will accept a blank field

 pattern="([01]?[0-9]|2[0-3])[0-5][0-9]"

I also want to use this pattern to allow null values OR a max and min length of only 4 characters...

 pattern=".{0}|.{4,4}"

I also have maxlength set - might be redundant

maxlength="4"

So basically I need a fixed character length (time as HHMM) of 4 characters or null - nothing in between....

I would have just been happy to use minlength but am receiving conflicting reports about its acceptance among browsers...

<input type="text" name="movie" maxlength="4" pattern="([01]?[0-9]|2[0-3])[0-5][0-9]" pattern=".{0}|.{4,4}" value='<?php echo $objResult["MOVIE"]; ?>'>
1
  • Try pattern="((?=.{4}$)([01]?[0-9]|2[0-3])[0-5][0-9]|)". Commented Jan 29, 2016 at 14:09

2 Answers 2

1

Try the following pattern:

(?:([01]?[0-9]|2[0-3])[0-5][0-9]|^$)

Which says: your pattern or an empty string (the ^$ part).
Hint: did not verify your pattern, just to give you an idea of the concept.

Sign up to request clarification or add additional context in comments.

1 Comment

It is a pattern attribute, the pattern is anchorex by default so there is no need specifying the anchors explicitly.
1

You have an optional digit in the first group: [01]?. It makes it possible to enter only 3 digits (leading 0 is optional).

Now, I understand you want to make the 0 obligatory and add a possibility to use an empty value. Just remove the ? quantifier from [01]? and use

<input pattern="(([01][0-9]|2[0-3])[0-5][0-9])?" title="4 digits please!" placeholder="0000"/>

The outer ()? makes the whole pattern optional (one or zero occurrences).

input:valid {
  color: green;
}
input:invalid {
  color: red;
}
<form name="form1"> 
 <input pattern="(([01][0-9]|2[0-3])[0-5][0-9])?" title="4 digits please!" placeholder="0000"/>
 <input type="Submit"/> 
</form>

Note: HTML5 pattern attribute value is anchored by default, i.e. the whole pattern is wrpapped into ^(?: and )$. You do not have to put ^ and $ between the pattern, and even if you add an alternative as Jan did, you do not need the ^/$ around the empty value.

The regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.