如何查找所有实例并在警报中显示 [英] How to find all instances and display in alert

查看:122
本文介绍了如何查找所有实例并在警报中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,用户可以输入或粘贴用逗号分隔的值,例如A123456,B123456,C123456,D123456

I have a textbox which users will type or paste comma separated values such as A123456,B123456,C123456,D123456

这些条目需要满足某些条件,其中之一是它们必须是七(7)个字符的长度...不多也不少.

These entries need to meet certain criteria, one of which is that they must be seven (7) characters in length...no more, no less.

如果他们输入的值超过七个字符,我需要显示一条警报,告诉他们他们输入的字符数太多.

If they enter a value that is more than seven characters, I need to display an alert telling them that they've entered a value with too many characters.

问题是,可能有成千上万个这样的条目,并且发出一条警报,提示说在成千上万个条目中的某个地方,有七个以上字符的一个或多个条目并没有帮助.

Problem is, there can be thousands of these entries and an alert that simply says that somewhere out of the thousands of entries there are one or more entries over seven characters isn't all that helpful.

我已经用以下代码部分解决了这个问题:

I've partially solved this with the following code:

val = document.getElementById("Textbox1").value;
val = val.split(',');
for(var i=0;i<val.length;i++){
    if((val[i].length !=7) && (val[i].length !=0)){
        alert("All entries must be seven (7) characters in lenght.  Please correct the following entries:\n" + val[i]);
        return false;
    }
}
return true; 
}

问题是,我一次只能返回一个不正确的条目.因此,用户必须更正其中一项,再次运行验证以查看是否还有另一项,然后重复该过程,直到找到全部.

The problem is, I can only return one incorrect entry at a time. So the user has to correct one, run the validation again to see if there is another one, and repeat the process until they find them all.

我想找出一种方法来显示警报中所有不正确的条目.非常感谢您的帮助.

I'd like to figure out a way to display all the incorrect entries in the alert. Any help is much appreciated.

推荐答案

使用 filter ,像这样:

What about using filter, like this:

var val = document.getElementById("Textbox1").value,
    err = $(val.split(',')).filter(function(){ return this.length != 7; }).toArray();
if (err.length) {
    alert("All entries must be seven (7) characters in length.  Please correct the following entries: \n" + err);
    return false; 
}
return true; 

演示

grep ,如下所示:

Or grep, like this:

var val = document.getElementById("Textbox1").value,
    err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
    alert("All entries must be seven (7) characters in length.  Please correct the following entries: \n" + err);
    return false; 
}
return true; 

演示

这篇关于如何查找所有实例并在警报中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆