Gagan
Gagan

Reputation: 294

How to prevent User to enter value at maxlength using jQuery

I want that user should not be able to enter text if he has more then 5 comma separated values in input box.

I have reached the value, but not sure. I think maxlength dynamic should do the trick.

I am trying to apply below code, but not working -

require(["jquery"],function($) {
    $("input.toEmail").keyup(function(e){
        var inputEmail = $("input.toEmail").val();
        var count = (inputEmail.match(/,/g) || []).length;  
        if(count >= 5){
            e.preventDefault();
            e.stopPropagation();
        }
    });
});

Upvotes: 2

Views: 1547

Answers (4)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

You can achieve it in this simple way.

Note:

  • Use split to "Split a string into an array of substrings"
  • Use slice to "extracts parts of a string and returns the extracted parts in a new string"
  • Use join to "returns the array as a string"

$("input.toEmail").keyup(function(e){
        var inputEmail = $(this).val();
        var strArray = inputEmail.split(/,/g);
     
        if(strArray.length >= 5){
            this.value = strArray.slice(0, 5).join(',');
        }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input  type="text" class="toEmail"/>

Upvotes: 4

Mayank Patel
Mayank Patel

Reputation: 1571

As far as I understand, you want to restrict to 6 comma restricted values hence it will include 5 commas. What I am doing here is that you can replace last(6th) comma so that it will allow only 6 values.

$(function() {
    $("input.toEmail").keyup(function(e){
       var length_comma = (($(this).val().match(/,/g)||[]).length)
        if(length_comma >= 6){          
          this.value = this.value.replace(/,\s*$/, "");
          e.preventDefault();
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input class="toEmail" type="text" name="toEmail" />

Upvotes: 1

klidifia
klidifia

Reputation: 1495

You should use keypress instead of keyup.

$("input.toEmail").keypress(function(e) {
  var inputEmail = $("input.toEmail").val();
  var count = (inputEmail.match(/,/g) || []).length;
  if (count >= 5) {
    e.preventDefault();
    e.stopPropagation();
  }
});

Upvotes: 0

John Archer
John Archer

Reputation: 2495

This is no tested code, but you may get the idea. Basically you set the content of you input back to the previous state if you reach the limit.

...
var inputEmail = $("input.toEmail").val();
var inputLength = inputEmail.length;

...

if (count >= 5) {
    $("input.toEmail").val(inputEmail.substring(0, inputLength - 1); // write back the previous content
}

Upvotes: -1

Related Questions