0

5 つのフィールドを持つフォームがあります。first namelast nameusernamepasswordおよびpasswordConfirmation

最初に言いたいのは、最も複雑な方法は望んでいないということです。これは、ライブになることのない非常に単純な Web サイト用であり、純粋にデモンストレーションを目的としたものであり、エラーのキャッチについて心配する必要はありません。有害なユーザー入力。

これまでのところ、私はこれを持っています:

function validateRegistrationForm(firstName, lastName, username, password, passwordConfirmation) {
alert("validate form function has been called");
//alert("function has been called");

//---


var firstName = firstName;
//alert(firstName);
var lastName = lastName;
//alert(lastName);
var username = username;
//alert(username);
var password = password;
//alert(password);
var passwordConfirmation = passwordConfirmation;
//alert(passwordConfirmation);

//---

//**The code that I have sectioned off here, I am unsure whether I need it or not, could someone please explain to me why I would do this, and not just reference the parameters in the function directly?**

// Check here if all the fields in the registeration form have been filled.

if ( firstname == null || firstname == "" ) {
    //firstname hasn't been filled out
}

if ( lastName == null || lastName == "" ) {
    //lastname hasn't been filled out
}

if ( username == null || username == "" ) {
    //username hasn't been filled out
}

if ( password == null || password == "" ) {
    //password hasn't been filled out
}

if ( passwordConfirmation == null || passwordConfirmation == "" ) {
    //passwordconfirmation hasn't been filled out
}
}

各フィールドが入力されているかどうかを確認する方法が必要です(ここにあると思います)。そうでない場合は、問題の入力要素の周りに赤い枠線やメッセージなどの通知を生成します問題を解決する方法について説明します。これは css で実行できることは知っていますが、最も効率的な方法はわかりません。

現在、次の 2 つの関数を作成しました。

function generateError(messageText, elementIdentifier) {
alert("error generator called");    
//var element = document.getElementById(elementID);
//var error = document.createTextNode(message);
//element.innerHTML = message;
alert("Element: " + elementIdentifier + ", Reason: " + messageText);
}

function validatePassword(password, passwordConfirmation) {
alert("password check called");
if (password == passwordConfirmation) {
    if (password.length < 8) {
        //password too short
        //alert("password\'s match but they are too short");

        return false;
    } else {
        //passwords match and the right length
        //alert("password\'s match and they are 8 characters or longer");
        return true;
    }
} else {
    //the two do not match
    //alert("they don\'t match")
    generateError("Passwords don\'t match", "password");
    return false;
}
}

このvalidatePassword()関数は、パスワードとパスワードの確認を 2 つのパラメーターとして受け取ります。これは既に機能していると思います。生成されたエラーをgenerateError()関数に渡して、それらをすべて配列に格納し、それらを 1 つずつループして表示します。ユーザーは何が悪いのですか。

4

2 に答える 2

1

複雑な定義. あなたのコードはすでに複雑すぎると思います。特典は、繰り返しがあることです。繰り返しを見たときはいつでも、その繰り返しをすべてループに結合する方法があるかどうかを自問してください。その結果、コードは少なくなりますが、通常は変更しやすいコードになります。たとえば、電話番号を追加する場合は、さらに 4 行のコードと別のパラメーターを追加する必要があります。これにより、未定義の電話番号を許可するコードをさらに追加しない限り、関数の下位互換性が失われます。「これ以上フィールドを追加するつもりはないので、それは問題ではありません」と言うかもしれません。私は自分自身で何回言ったかわかりませんが、最終的には自分の言葉を食べて、自分の機能に手術をしなければなりませんでした. その上、その優れたエンジニアリング。

また、validateRegistrationForm 関数に戻りましょう。今のやり方では、onsubmit によってトリガーされると思いますが、各フィールドでユーザーに即座にフィードバックを与えることで、JavaScript の機敏さを利用してみませんか? これを validateRegistrationElement に変更すると、onchange という名前になります。評価されるテキストボックスの 1 つのパラメーターのみを渡します。そうすれば、「これ」を使うことができます。したがって、各テキストボックスは次のようになります。

 <input type="text" id="firstname" onchange="validateRegistrationElement(this)" />

また、各テキスト ボックスの隣にフィードバック ボックスを配置して、煩わしいアラート ポップアップを取り除きましょう。CSS クラス名「エラー」と「成功」を使用してフィードバック ボックスのスタイルを設定し、それぞれを赤または緑にすることもできます。

 <div id="firstnameFeedback"></div>

...などなど。

CSS:

 .error {background-color: pink; border: 1px dashed red; color: white} 
 .success {border: 1px dashed green;}

関数に各フォーム要素の詳細をロードする代わりに、命令をオブジェクトの配列である一種の構成変数に分けましょう。配列の各メンバーは 1 つのフォーム要素を表すため、この場合、配列のメンバーは 4 つになります。これらは、関数がエラーを報告するために知る必要があるすべてを含むオブジェクトです。私の提案は、各オブジェクトにフォーム要素の ID、ラベル、要件 (独自のフィードバック メッセージとペアになった正規表現の配列が理想的ですが、文字列の長さでシンプルにしましょう)、および特別な条件を含めることです。パスワードの一致のため。

 var myFields =
  [
   {
    "id": "firstname",
    "label": "first name",
    "minLength": 1 //in other words, the field is required
   },
  {
    "id": "lastname",
    "label": "last name", 
    "minLength": 1
   }, 
  {
    "id": "password1",
    "label": "first password", 
    "minLength": 6,
    "maxLength": 8,
    "mustMatch": "password2"
   },
  {
    "id": "password2",
    "label": "second password", 
    "minLength": 6,
    "maxLength": 8,
    "mustMatch": "password1"
   }, 
  ]

これは複雑すぎますか?私はそうは思わない。これで、バリデータ関数が到達できるレゴのバケツができました。要素を簡単に追加または削除できます。必要に応じて後で機能を追加することもできますが、機能を壊すことはありません (パスワードの maxlength のように、機能から除外しました)。お見せします。これが新しいバリデータ関数です。これは、ユーザーがフィールドの値を変更するたびに呼び出されることに注意してください。html で "this" を使用したため、関数はどれかを認識します。

 function validateRegistrationElement(field) {
  var message = ""; //declare an empty string literal for the message
  for (i=0;i<myFields.length; i++){ //loop through each array element until we find the object
   if(myFields[i].id == field.id){ //once we've found the config object
    if(myFields[i].minLength > field.value.length){ //if the field is shorter than what's allowed
     message += myFields[i].label + " must be longer than " + myFields[i].minLength;
    }
    if (typeof(myFields[i].mustMatch) != 'undefined'){ //if the field must match another...
     if(field.value != document.getElementById(myFields[i].mustMatch)){ //...does it match
      message += myFields[id].label +" must match "+myFields[id].mustMatch;
     }
    }
   document.getElementById(field.id + "Feedback").innerText = message;
   if (message.length > 0) {setClass(field.id, "error")} //if there an error message, highlight red
   else{setClass(field.id, "success")}//otherwise, highlight green
   }
  }
 }

これはパスワードも処理するため、追加の機能は必要ありません。

この関数は CSS を管理し、上記の関数によって呼び出されます。

 function setClass(id, className) {
    document.getElementById(id).className = "";
    document.getElementById(id).className = className;
    document.getElementById(id+"Feedback").className = "";
    document.getElementById(id+"Feedback").className = className; 
 }
于 2013-01-15T00:44:25.277 に答える
0

優れたjQuery Validation プラグインを試してください。

もう少しマークアップが必要で (デモとドキュメントを参照) $("#yourForm").validate();、.

于 2013-01-15T00:53:08.097 に答える