doufang2228 2017-08-03 18:20
浏览 153

jquery插件过滤表单字段输入与正则表达式的十进制/浮点值 - 验证的正则表达式模式似乎没有工作

Background: using JQuery plugin for input text field filtering and regex (tried several variations actually) with symfony 3.x

jquery http://www.thimbleopensource.com/tutorials-snippets/jquery-plugin-filter-text-input

Goal: Have the form field accept only positive float / decimal up to 3 decimal places.

Acceptable:

3.24
.56
3456.789

Not Acceptable:

-3.65
-.67
3.6.5
3c.56
5g

I have used reg exp testers such as https://www.freeformatter.com/regex-tester.html to build/find a reg ex that works such as;

^(?:[1-9]\d*|0)?(?:\.\d+)?$ or ^[0-9]*[.][0-9]+$

Both work in the tester.

I am using regex like;

$('#name of the form field').filter_input({regex: "^[0-9]*[.][0-9]+$"});

They don't seem to work with the jquery plugin. The plugin might be buggy or am I doing something wrong?

  • 写回答

2条回答 默认 最新

  • doubingling4706 2017-08-03 18:41
    关注

    It seems like the plugin is just accepting character groups, and isn't matching the full pattern. So you can basically just restrict the type of characters that can be inserted, but you can't specify a full pattern that has to be matched.

    Here's a quick and dirty solution that won't require an additional plugin:

    $("#myField").on("keyup change", function () {
        var self = $(this), lastValid = self.data("lastValid") || "";
        if (self.val().match(/^\d*\.?\d{0,3}$/)) {
          self.data("lastValid", self.val());
        } else {
          self.val(lastValid);
        }
    });
    

    It basically just stores the last valid input and sets the field back to the last valid input once something invalid was entered.

    The pattern I'm matching against is: ^\d*\.?\d{0,3}$

    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来