ค้นหาเว็บไซต์

javascript - ฟังก์ชันตรวจสอบความถูกต้องที่สั้นกว่าสำหรับฟิลด์ที่จำเป็น


ในแอปพลิเคชัน HTML ที่ใช้ TypeScript ฉันมีฟอร์ม 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

นี่จะแสดงข้อความที่ต้องการเริ่มต้น

  <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>

คำตอบ #2

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

คุณสามารถสร้างฟังก์ชันที่ค้นหาข้อผิดพลาดได้หรือไม่? คุณจะเรียกใช้ฟังก์ชันแบบนี้: catErrors(Field1).
สิ่งนี้จะช่วยให้โค้ดของคุณสั้นลง สิ่งที่คุณต้องทำคือเพิ่มฟิลด์แรกด้วยตนเองเพื่อเริ่มต้น และทุกอย่างที่ตามมาจะใช้ฟังก์ชัน catErrors() หวังว่าสิ่งนี้จะช่วยได้นะ!