0

I'm trying to create perfect number validation using JQuery. I saw This website ealier, but if you type some of the Not allowed numbers, then it still show as valid number.

How I can create this JQuery validation for example numbers ONLY from Allowed list?

Allowed:

  • 1
  • 1.2454554
  • 0.25325
  • 654664

Not allowed:

  • 0.
  • 05
  • 0999
  • 0.435.53
  • 0,53
  • dfgdfhjghfs

Code:

<script>
$('#ch_rate').keyup(function(){
  var rate_input = $(this).val();
  var rate_regexp = new RegExp('^\d+(\.\d+)*$');
  if (rate_input.replace(/ /g,'').length > 1 && rate_input.charAt(0) == 0 && rate_input.indexOf('.') == 0 || !rate_regexp.test(rate_input)) {
   // invalid
  }
});
</script>

Input:

<input id='ch_rate' type='text' pattern='[0-9\.]'/>

1 Answer 1

3

I use /^((0|[1-9]\d*)(\.\d+)?)?$/ to validate the strings you provide.

(0|[1-9]\d*) to check if the string starts with 0 or positive integers.

(\.\d+)? to check if there is one set of decimal point with any digits or not.

((0|[1-9]\d*)(\.\d+)?)? the last question mark is to check if string is empty or not.

Here's a test for both allowed and not allowed list:

let rate_regexp = /^((0|[1-9]\d*)(\.\d+)?)?$/;

let List = [
  "1",
  "1.2454554",
  "0.25325",
  "654664",
  "", // add an empty string here
  "0.",
  "05",
  "0999",
  "0.435.53",
  "0,53",
  "dfgdfhjghfs"
];

List.forEach(function(value){
  document.body.innerHTML += `${value} : ${rate_regexp.test(value)}<br>`;
})

And here's a demo:

$('#ch_rate').keyup(function(){
  let $this = $(this);
  var rate_input = $this.val();
  var rate_regexp = /^((0|[1-9]\d*)(\.\d+)?)?$/;
  if (!rate_regexp.test(rate_input)) { // invalid
    $this.css({color: "red"});
  }
  else{
    $this.css({color: "black"});
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='ch_rate' type='text' pattern='[0-9\.]'/>

Sign up to request clarification or add additional context in comments.

Comments