-4

jsp 中的文本框,只允许文本数字和逗号。

这是为了分隔用户标识。

每个用户 ID 的长度必须为 8 个字符,我需要在文本框中输入多个用户 ID。

例如:

正确的格式如下

asakthi1,psubhadr,tpradee4

它不应该像结束一样(结尾有逗号。)(格式不正确)

asakthi1,psubhadr,tpradee4,

这是我需要使用 javascript 来完成的。(请不要使用 Jquery。)

我对此摸不着头脑..任何帮助将不胜感激。

4

1 回答 1

1

You could attach an onchange event handler to the <input type="text"> that will perform the validation using a regular expression like, for instance, this one: ^(([A-Za-z0-9]{8}),)*[A-Za-z0-9]{8}$.

If a username is a combination of 8 letters or numbers, this expression would accept any number of usernames followed by comma, and at least one final username without a comma. Notice the {8} element forces a match of exactly 8 characters.

If validation fails, it's up to you how to show it to the user. This example will be showing an alert and clearing the input.

<input type="text" onchange="if (!validate(this.value)) { alert('incorrect value'); this.value = ''; }">

<script>
function validate​(value){
    return value.match(new RegExp("^(([A-Za-z0-9]{8}),)*[A-Za-z0-9]{8}$")) != null;
}​
</script>

Here is a sample JSFiddle to see the expression at work.

于 2012-10-18T15:24:26.950 回答