0

i got an aesy formular with a few input fields that i must validate.

the Question is: how can i check that if the two input fields are empty? and than give out an alert?

<input type="text" class="field1" name="vorname"  id="vorName"/>
<input type="text" class="field1" maxlength="30" name="vorname" id="nachName"/>

the Alert should than look like this: The inputfields: Vorname and Nachname are not correct/empty!

Tushar
  • 85,780
  • 21
  • 159
  • 179

1 Answers1

0

Instead of showing alert you can use HTML5's required attribute for validation.

<input type="text" class="field1" name="vorname" id="vorName" required />
<!--                                                          ^^^^^^^^ -->
<input type="text" class="field1" maxlength="30" name="nachname" id="nachName" required />
<!--                                                                           ^^^^^^^^ -->

required:

This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden, image, or a button type (submit, reset, or button). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate.

If some browser is not supporting this, you can use polyfill.

solved the problem:

function proof() {
    var elements = document.getElementsByClassName("field1");

    var fehler = [];
    var meldung = "Bitte noch folgende(s) Eingabefeld(er) füllen: \n";

    for (var i = 0; i < elements.length; i++) {
        if (i != 3) {
            if (!elements[i].value) {
                fehler.push(elements[i].name);
            }
        }
    }

    for (var i = 0; i < fehler.length; i++) {
        meldung += " - " + fehler[i] + "\n";
    }

    if (fehler.length > 0) {
        alert(meldung);
        return false;
    }
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • jeah... the name of the second input is wrong ^^ sry bout that. I know about required, but i need an Alert. – Diego Bell Jul 08 '15 at 13:31