Javascript验证允许最多3个逗号和1个逗号中的20个字符?
$('#txt_tags').keyup(function () {
var tags = $(this).val().split(',');
if (tags.length > 13)
alert('there is more than 13 tags');
});
答案 0 :(得分:0)
您只需迭代标记数组并检查它们的长度。
$('#txt_tags').keyup(function () {
var tags = $(this).val().split(',');
if (tags.length > 13)
alert('there is more than 13 tags');
tags.forEach(function(tag){
if(tag.length > 20)
alert("Tag has more than 20 characters");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt_tags" />
答案 1 :(得分:0)
试试这个:
$('#txt_tags').keyup(function () {
if($(this).val().match(/^([^,]*,){14,}|([^,]{21,})/g))
alert("NOT VALID!");
});
([^,]*,) --> match every comma separated by every char except comma
{14,} --> match it 14 or more time
| --> or
[^,] --> every char except comma
{21,} --> match it 21 or more time