简体   繁体   中英

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>

如果使用HTML5是一个选项,那么你可以在输入中包含一个模式属性,例如使用Pranav C Balan的正则表达式:

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM