0

I have a regular expression to validate Feet and inches entered into a feet input field.

RegEX

^([1-2]?[0-9]{1,3})\'([0-9]|[0-1]{2})\"$

HTML

<label for="ft">Feet:</label>
<input type="text" name="ft" id="ft" value="#form.ft#">

jQuery

<script>
$.mask.definitions['h'] = '^([1-2]?[0-9]{1,3})\'([0-9]|[0-1]{2})\"$';
$('#ft').mask('h',{placeholder:'0\'0"'});
</script>

or

$('#ft').mask('???0\'0?0"',{placeholder:'0\'0"'});

What if the optional characters are in the beginning? And you have two spots that are optional?

What I am trying to do:
Is when the user gets to the page in that text box it will already read 0'00" so then when they start filling it out it will just start filling it out keeping the " ' " and " " " already in the box for them. On the feet side going up to 2000 and on the inches side only allowing up to number 11.

I am having trouble either inserting a mask like 0'00" or what to have the symbols stay there and them to start entering from left to right.

Any assistance would be greatly appreciated!

  • You'll probably want to use some sort of masked input plugin rather than rolling your own code. – James Thorpe Apr 10 '15 at 16:26
  • You would escape the quotes, eg imagine some imaginary plugin: `$('input').mask('9999\'99"')` – James Thorpe Apr 10 '15 at 16:29
  • [Here's a quick demo](http://jsfiddle.net/JamesThorpe/n3vvny78/) based on [this plugin](http://digitalbush.com/projects/masked-input-plugin/). In the docs it shows how you can use regexes to customise the masks even further (eg to restrict the 2nd part to 11") – James Thorpe Apr 10 '15 at 16:33
  • No, this is the first time I've ever seen or used this plugin, but it should be a good starting point for you to research either this one further or take a look at what other plugins are available, barring anyone coming and posting a full answer. – James Thorpe Apr 10 '15 at 16:39
  • Perhaps a more sensible solution for this could look like this: http://jsfiddle.net/ad67284f/ …? (Add polyfill of choice for older browsers.) – CBroe Apr 10 '15 at 17:03

1 Answers1

0

You can use this:

^([1-2]?[0-9]{1,3})?\'(0?[0-9]|[0-1]{2})?\"$

It validates, but makes the sections optional.

As for input keeping ' and ", put them into capturing groups:

^([1-2]?[0-9]{1,3})?(\')(0?[0-9]|[0-1]{2})?(\")$

Then you can analyze the groups $1, $2, $3, and $4, where $1 and $3 would be the values, and $2 and $4 are ' and " respectfully. As the user types, perhaps parse the input, split it up using this regex, and replace their input while restoring the caret position. Optionally, you could just wait for the input to lose focus and replace the contents with the resulting parsed value instead.

Example:

var r = "0'00\"".match(/^([1-2]?[0-9]{1,3})?(\')(0?[0-9]|[0-1]{2})?(\")$/)
// Result: r == ["0'00"", "0", "'", "00", """]

Now, you can replace the input contents with the joined values:

r.splice(1).join("");
Community
  • 1
  • 1
James Wilkins
  • 6,836
  • 3
  • 48
  • 73