0

I could not find an answer for this. So I hope it's not redundant..

Have a simple form element:

<label>Email Address:</label>
<input type="text" onblur="validateEmail(this)" />

And I'm running a validation script to check whether this input value (onBlur) is valid. Works great!

Now.. what I'm trying to do is keep the script universal - so I do not have to rely on class names or IDs to make it work.

So what I want to know is how to take action on this field if the value is NOT an email address. Specifically, I want change the color of the label and put a red border on the field itself.

Here's the script that does not work:

var inputTextTest = field.value;
var filter = /^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*?)\s*;?\s*)+/;

if ( filter.test(inputTextTest) ) {
    var name = field;
    $(this).focus();
    $(this).css("border","1px");
    $(this).css("border-color","red");
} else {
    $(this).css("border", "none");
}

I can see that my call to $(this) isn't working. So how do I take action on this particular field and keep the script totally universal (i.e., not dependent on specific classes or ID names)?

Thanks to all in advance for your help!

4

4 に答える 4

3

上部で使用しているように、パラメーター参照thisはであると思います:fieldfield.value

validateEmail(field) {
    var inputTextTest = field.value;
    var filter = /^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*?)\s*;?\s*)+/;

    if ( filter.test(inputTextTest) ) {
        var name = field.name;
        $(field).focus().css("border","1px solid red");
    } else {
        $(field).css("border", "none");
    }
}
于 2013-04-06T20:30:51.460 に答える
1

関数宣言が次のように見えると仮定するfield代わりに試してくださいthisvalidateEmail(field)

内部ではオブジェクトとして関数onblurに渡しthisていますが、関数の引数を宣言したときに使用したパラメーター名を使用する必要があります

于 2013-04-06T20:30:57.773 に答える
0

スクリプトを関数に入れ、オブジェクトを引数として取り、オブジェクトに対してすべてを実行します。

于 2013-04-06T20:33:24.873 に答える
0

汎用にするために、既存の検証ライブラリのいずれかを使用することをお勧めします。

https://github.com/DiegoLopesLima/Validate#readme

$(this) が機能しない理由は、それが定義されておらず、参照を作成したコールバックまたは関数にいないためです。

一般的なループを実行して $(this) を使用するには、次のようにする必要があります。

$('input').each(function() {
  $(this)  // will now reference each element.
});
于 2013-04-06T20:27:54.913 に答える