简体   繁体   中英

Regex to validate textfield with csv format using javascript

I tried with the following regular expression

/^([a-z0-9])+(,[a-z0-9]+)*$/

My text field string looks like the following csv format as

123,456,789,012

But the above expressions fails for me, main thing is whitespaces are not allowed with the given text field string.

  1. If you want to validate textfield with value like csv format ,

    you can use : /^([a-z0-9]+(?:,[a-z0-9]+)*)$/gm

    Which will accept 123,456,789,012

    And will reject 123, 456, 789, 012 // Those containing spaces

  2. If you want to match something like this (num,num,num,num)

    you can use :

    /^(\\([a-z0-9]+(?:,[a-z0-9]+)*\\))$/gm

DEMO

Explanation :

在此处输入图片说明

If I understand you correctly, here's the version with white-spaces allowed:

var pattern = /^[a-z0-9]+(?:, ?[a-z0-9]+)*$/;
!!pattern.exec('123,456,789,012'); // true
!!pattern.exec('123, 456, 789, 012'); // true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM