Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript validation to allow maximum of 3 commas

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

123,456,789,0000

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

like image 985
Shefali Aggarwal Avatar asked Jan 28 '12 07:01

Shefali Aggarwal


1 Answers

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

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

like image 57
Nobody Avatar answered Sep 21 '22 21:09

Nobody