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}$

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘