2016-04-04 9 views
2

typescriptを使用したHTMLアプリケーションでは、私はHTMLフォームを持っています。このフォームにはいくつかの必須フィールドがあります。私のtypescriptファイルでは、私はこのようなエラーメッセージ構築しています:必要とされる多くのフィールドがある場合、あなたが見ることができるように必要なフィールドの検証機能の短縮

hasErrors() { 
    let errorCount = 0; 

    if (!item.Field1()) { 
     this.ErrorText('"Field1"'); 
     errorCount++; 
    } 
    if (!item.Field2()) { 
     if (errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "Field2"'); 
     else 
      this.ErrorText('"Field2"'); 
     errorCount++; 
    } 
    if (!item.Field3()) { 
     if (errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "Field3"'); 
     else 
      this.ErrorText('"Field3"'); 
     errorCount++; 
    } 

    // ... 

    if (errorCount > 1) 
     this.ErrorText("The fields " + this.ErrorText() + " are required."; 
    else if (errorCount == 1) 
     this.ErrorText("The field " + this.ErrorText() + " is required."; 
    else 
     return false; 
    return true; 
} 

を、この機能は非常に長くなります。同じ結果を得るためのより良い/より短い方法がありますか?

答えて

1
function catErrors(field){ 
    if (!item.field) { 
     if (this.errorCount > 0) 
      this.ErrorText(this.ErrorText() + ', "' + field + '"'); 
     else 
      this.ErrorText('"' + field + '"'); 
     this.errorCount++; 
    } 
} 

エラーを探す関数を作成できますか? 次のような関数を呼び出します:catErrors(Field1)
コードを短縮するのに役立ちます。最初のフィールドを手作業で追加して、それに続くすべてのフィールドにはcatErrors()という関数を使用するだけです。お役に立てれば!

+0

ありがとう、それは私が探していたものです。 –

3

これはデフォルトが表示されますが、MSGを必要と

<form action="includes/loginprocess.php" method="POST"> 
    <input type="text" name="user" placeholder="Username" required> 
    <input type="password"name="pass" placeholder="Password" required> 
    <input type="submit" value="Login"> 
    </form> 
0

あなたは、彼らが欠けているブランクいるユーザーに伝えるためにしようとしている、それについて考えるために来ます。それは本当に貧しいですか?欠落している空白を検出し、「Field xxx is missing」というメッセージを返すのはどうですか?たとえば、ユーザー名とパスワードの2つの空白があり、どちらも入力しない場合は「ユーザー名が必要です」と指摘しても構いません。

関連する問題