Zagadnienie: Proste warunki if

Na egzaminie często sprawdzamy: czy pole jest puste, czy tekst jest za krótki, czy liczba jest w zakresie.

Najczęstsze warunki:
if (pole.value === "") → puste pole
if (pole.value.length < 3) → za krótki tekst
if (liczba < 0 || liczba > 100) → poza zakresem

Wersja A – najprostsza (egzaminowa)



function sprawdzA() {
    let login = document.getElementById("loginA").value;
    let komunikat = document.getElementById("komunikatA");

    if (login === "") {
        komunikat.innerHTML = "Pole nie może być puste!";
        komunikat.className = "komunikat blad";
    } else if (login.length < 3) {
        komunikat.innerHTML = "Login musi mieć co najmniej 3 znaki!";
        komunikat.className = "komunikat blad";
    } else {
        komunikat.innerHTML = "Login poprawny: " + login;
        komunikat.className = "komunikat ok";
    }
}

Wersja B – addEventListener



const wiekB = document.getElementById("wiekB");
const komunikatB = document.getElementById("komunikatB");

document.getElementById("btnB").addEventListener("click", function() {
    let wiek = Number(wiekB.value);

    if (wiekB.value === "") {
        komunikatB.innerHTML = "Podaj wiek!";
        komunikatB.className = "komunikat blad";
    } else if (wiek < 0 || wiek > 120) {
        komunikatB.innerHTML = "Wiek musi być między 0 a 120!";
        komunikatB.className = "komunikat blad";
    } else {
        komunikatB.innerHTML = "Wiek zaakceptowany: " + wiek;
        komunikatB.className = "komunikat ok";
    }
});

Wersja C – kompaktowa



const hasloC = document.getElementById("hasloC");
const komC = document.getElementById("komunikatC");

document.getElementById("btnC").onclick = () => {
    const h = hasloC.value;
    if (h === "") {
        komC.innerHTML = "Hasło nie może być puste!";
        komC.className = "komunikat blad";
    } else if (h.length < 5) {
        komC.innerHTML = "Hasło za krótkie (min. 5 znaków)!";
        komC.className = "komunikat blad";
    } else {
        komC.innerHTML = "Hasło zaakceptowane";
        komC.className = "komunikat ok";
    }
};