JavaScript Function Error Frame

1

asked by anonymous 04.02.2014 / 19:11

1 answer

1

Below is an example using javascript to change the element's CSS class after some error condition has been checked. Click here to view the sample in JSFIDDLE.

In the example I use the events CHANGE and BLUR . The first one is fired when a change occurs in the field and the second fires whenever the field loses focus.

HTML

<input id="foo" class="ok" type="text" onchange="verificaCampo()" onblur="verificaCampo()">
</input>

CSS

.ok {
}
.erro {
    border: 1px solid red;
}

JAVASCRIPT

function verificaCampo() {
    var foo = document.getElementById("foo");

    if (foo.value !== "entendi" ) { // adicione alguma cond de erro
        foo.className = "erro";
    } else {         
        // nao existem erros       
        foo.className = "ok";
    }
}

You can also use an event handler that checks if the fields are correctly populated at the time the client attempts to submit the form. This way the system becomes more responsive since it does not have to wait for the server to respond to know that something is wrong on the form. But care , do not forget to test the data on the server as well because there is no guarantee of the data coming from the client (javascript may be disabled on the client, for example).

    
04.02.2014 / 20:37