简体   繁体   English

字段验证脚本问题

[英]Problems with field validation script

I have some javascript code that reads: 我有一些JavaScript代码如下:

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

This is supposed to provide a visual cue to the user, about the field he or she is typing in, however, this just flips the colour on every keypress. 这应该向用户提供有关他或她正在键入的字段的视觉提示,但是,这只会在每次按键时翻转颜色。

Your callback function for the keyup event should be take an eventObject parameter . 您的keyup事件的回调函数应采用eventObject参数 This exposes a which property that provides information about the keycode/character code that was pressed . 这暴露了which属性该属性提供有关所按下的键控代码/字符代码的信息

You should pass that to your test to see if a keypress is valid/invalid. 您应该将其传递给测试,以查看按键是否有效/无效。

Not knowing what response the test function returns, you can try like this: 不知道test函数返回什么响应,您可以这样尝试:

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

Yeah, it heavily depends on the regex you are matching. 是的,这在很大程度上取决于您要匹配的正则表达式。

You should try to debug it first: 您应该首先尝试调试它:

(I will be continuing with Sarfraz's code). (我将继续使用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!');
});

Also, since you are using jQuery, you should rely more on its 'write less' philosophy. 另外,由于您使用的是jQuery,因此应更多地依赖于它的“少写”哲学。

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

Maybe you should paste the regular expression code and what you are trying to achieve. 也许您应该粘贴正则表达式代码以及您要实现的目标。

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

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