繁体   English   中英

字段验证脚本问题

[英]Problems with field validation script

我有一些JavaScript代码如下:

$(this).keyup(function () {
  if(regex.test(this.value))
    this.style.backgroundColor=config.validColor;
else
    this.style.backgroundColor=config.invalidColor;
});

这应该向用户提供有关他或她正在键入的字段的视觉提示,但是,这只会在每次按键时翻转颜色。

您的keyup事件的回调函数应采用eventObject参数 这暴露了which属性该属性提供有关所按下的键控代码/字符代码的信息

您应该将其传递给测试,以查看按键是否有效/无效。

不知道test函数返回什么响应,您可以这样尝试:

$(this).keyup(function () {
  if(!regex.test(this.value))
    this.style.backgroundColor=config.invalidColor;
else
    this.style.backgroundColor=config.validColor;        
});

是的,这在很大程度上取决于您要匹配的正则表达式。

您应该首先尝试调试它:

(我将继续使用Sarfraz的代码)。

$(this).keyup(function () {
  if(!regex.test(this.value))
    this.style.backgroundColor=config.invalidColor;
    $('#debug').html('invalid color');
else
    this.style.backgroundColor=config.validColor;        
    $('#debug').html('valid color!');
});

另外,由于您使用的是jQuery,因此应更多地依赖于它的“少写”哲学。

$(this).keyup(function () {
  if(!regex.test(this.value))
    $(this).css('backgroundColor', config.invalidColor);
    $('#debug').html('invalid color');
else
    $(this).css('backgroundColor', config.validColor);
});

也许您应该粘贴正则表达式代码以及您要实现的目标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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