Jquery plugin filtering regex field input fields for decimal / float values ​​- checked regex patterns don't seem to work

Background : using jQuery plugin to filter input textarea and regex (actually tried several options) with symfony 3.x

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

Purpose . Let the form field only accept a positive float / decimal value up to 3 decimal places.

Acceptable:

3.24
.56
3456.789

      

Not allowed:

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

      

I have used reg exp testers like https://www.freeformatter.com/regex-tester.html to create / search reg ex that works like:

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

or ^[0-9]*[.][0-9]+$

Both work in the test.

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. Perhaps the plugin might be a bug or am I doing something wrong?

+3


source to share


2 answers


It looks like the plugin is just accepting groups of characters and doesn't match the whole pattern. Thus, you can simply limit the type of characters that can be inserted, but you cannot specify the complete pattern to be matched.

Here's a quick and dirty solution that doesn'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);
    }
});

      



Basically it just stores the last valid input and sets the field back to the last valid input as soon as something invalid has been entered.

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

0


source


Check if this works for you. Don't need to use any plugin. https://jsfiddle.net/kajalc/dtky1okL/



<input type="text" id="tester">
<div class="alert"></div>
  $("#tester").on("focusout", function(){
    var value = $(this).val();
  var patt = new RegExp("^[0-9]*[.][0-9]+$");
    if(patt.test(value)){
    $(".alert").text("Match Found!!");

  }else{
    $(".alert").text("No Match Found!!");
  }
});

      

0


source







All Articles