Don't Input more than 20 comma separated or new-line separated serial no and alpha-numeric in textarea in angularjs


Here is my problem statement. Any help will be great.

Users are allowed to input text in the textarea with below restrictions.

  • Only AlphaNumeric entries(Serial nos) are allowed.

  • Only 20 Entries (It can be comma separated like FVO01,FVO02,FVO03 ..)
    or new line like
    FVO03 etc.

  • User can copy and paste from notepad or excel sheet so in doing so there might be more than 1 new line between 2 serial numbers, so have to take care of that also.

My Approach:
Trim all the spaces first.
Replace all new line(/n) characters with comma(,). If it’s already comma-separated entry then conversion won’t affect anything.
Count length and alert if it is more than 20.

Here is what I have tried till now, somehow capture and replace new line isn’t working.

Looking for a better solution satisfying all of above conditions. Thanks

function checkValidations(newValue) {
                    $ctrl.serialNos = newValue;
                    var comma = "";                     
                    if($ctrl.serialNos) {
                    comma = $ctrl.serialNos.replace(/\s/g, "");
                    comma = $ctrl.serialNos.replace(/\n/g, ",");
                    comma = comma.split(",");
                    var alphaNumeric = /^[(a-z)(A-Z)(0-9),]+$/;
                    if($ctrl.serialNos) {
                    if(!($ctrl.serialNos.match(alphaNumeric))) {
                        alert("Please enter only Alphanumeric values")
                    if (comma.length > 21 ) {                           
                        alert("You can not enter More than 20 serial nos");


\s matches all whitespace, including new lines, so you will need to replace the new lines first.

comma = $ctrl.serialNos.replace(/\n+/g, ",");
comma = comma.replace(/\s/g, "");

Answered By – Unmitigated

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published