DXB-DEV
DXB-DEV

Reputation: 579

HTML input field restricted with regular expression pattern

I want to restrict the user input in an HTML input field.

It is a field which accepts the weight in decimal and the unit(kg, lbs, g, t etc).

Following are few sample input which are valid:

10.45 kg
125.5 kg
120.35 lbs
160 lbs
1200.16 g
24.6 t

I am using the JQuery plugin mentioned in the below URL: http://www.thimbleopensource.com/tutorials-snippets/jquery-plugin-filter-text-input

But it is not working with complex patterns. Can anyone please help me with the regular expression to achieve the result?

Find the complete code below:

<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script src="/js/jquery/jquery-2.1.4.js" type="text/javascript"></script>
<script src="/js/jquery/jquery.filter_input.js" type="text/javascript"></script>

<script type="text/javascript">
<!--//

$(document).ready(function(){
   $('#input_2').filter_input({ regex: '\d+(?:.\d+)?\s(?:kg|lbs|t)' });
});

//-->
</script>

</head>

<body>

Weight: <input id="input_2" type="text" size="20" />

</body>
</html>

Upvotes: 1

Views: 4764

Answers (2)

Jeremy Jones
Jeremy Jones

Reputation: 5631

If using HTML5 is an option then you could just include a pattern attribute on the input, for example using the regex from Pranav C Balan:

<input type="text" name="weight" value="" pattern="^\d+(?:\.\d+)?\s*(?:kg|lbs|t)$" />

Upvotes: 3

Phylogenesis
Phylogenesis

Reputation: 7880

The below is not the correct answer in this instance. As @stribizhev commented, the plugin you are using does not allow complex regex validation. It checks each individual character you type in against the regex, rather than validating the field as a whole.

This sort of validation does not seem to possible with your plugin, unfortunately.


The following matches all your examples:

^\d+(\.\d+)?\s(g|lbs?|kg|t)$

This breaks down as follows:

^                # Matches start of string
\d+              # 1 or more digits
(\.\d+)?         # Optionally followed by a decimal point and more digits
\s               # Whitespace
(g|lbs?|kg|t)    # Any of g, lb, lbs, kg, t
$                # Match end of string

Example here (regex101.com).

Upvotes: 0

Related Questions