Take the 2-minute tour ×

I want a Javascript validation that allows maximum of 3 commas in a text field user to enter a number or text in format


meaning 3 Commas(,) are allowed, there could be any number of digits/letters between commas. User may choose to enter only 2 Commas i.e. 3 values but max number of Commas that would be allowed are 3 for eg a,bb,ddddd,eeeee (4 tags) a,cc,bbbbb (3 tags)

What I am trying to achieve is user is allowed to enter only 4 comma separated tags thus making sure user cannot flood the article with 100's of tags

share|improve this question
What have you tried so far?? –  Fahim Parkar Jan 28 '12 at 7:17
add comment

2 Answers

up vote 5 down vote accepted
var txt = '123,456,789,0000';
if( /^([^,]*,){0,3}[^,]*$/.test( txt ) ){
    // good
    // bad

change the * to a + if you want to ensure that there aren't two commas in a row, e.g.: 12,,345

share|improve this answer
thanx alot.. it reaaly helped me alot. –  Shefali Aggarwal Jan 28 '12 at 7:49
This validation works perfectly fine, but i have a doubt, i want to make sure that user can not enter more then 3 commas in input box, i.e if a user has entered 3 commas, the user will not be able to even enter 4th comma. I hope, i am making myself clear. –  Shefali Aggarwal Jan 28 '12 at 13:42
This does that. Matches "Any non-comma followed by a comma" 3 times. The only place a comma is allowed is in the {0,3} which won't match more than 3 times –  zyklus Jan 29 '12 at 4:22
add comment

If you have control on server side, I suggest doing the validation there.

Because If you try to do the validation on the client using java script, it can be circumvented by either turning off java Script all together, or using Firefox's FireBug extension by manipulating or manually executing a request, bypassing your java script validation altogether.

But if you really still want to do some kind of validation in javascript, you can do something like the following:

Given this input field <input id="txtInput" type="text" />

You could bind a keyup event (pay attention to people attempting to paste from the clipboard, keyup will not catch it if they do it via context menu)

   //This splits up the string value of the text box into an array 
   //wherever a coma appears
   var tags = $(this).val().split(',');

   //These would be your tags, without the coma, count them to find out how many
   //the user tried to enter.
   if (tags.length > 4)
       alert('there is more than 4 tags');

Of course this is only an example, but you could adapt the idea to your needs. You don't have to bind this to the keyup event, you could bind this to a click event on the submit button or something, it all depends on your needs.

share|improve this answer
add comment

Your Answer


