Skip to content Skip to sidebar Skip to footer

Validate A Form Using Javascript

I am a beginner and I have written a code for validating the form as: function validateForm(){ var x=document.forms['myForm']['fname'].value; if (x==null || x==''){ alert('First na

Solution 1:

This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:

<script>functionvalidate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
    if (x==null || x==""){
        y.innerHTML = "Error";
    }
}
</script>

The HTML form is:

<formname="myForm">
First name: <inputtype="text"name="fname"onBlur = "validate()"><divid = "errorResponse"></div><inputtype="submit"value="Submit"></form>

The div can be designed in CSS to red color to get user attention and many more tricks can be played.

Solution 2:

replace your input element's code by following

<inputtype="text" onblur="return validateForm();" name="fname">

i guess thats what you are looking for

Solution 3:

<html><head><scripttype="text/javascript">functionvalidateForm(oForm){
    var els = oForm.elements;
    for(var i = 0; i < els.length; i++){
       if('string' === typeof(els[i].getAttribute('data-message'))){
          returnvalEl(els[i]);
       }
    }
} 

functionvalEl(el){
    var method = el.getAttribute('data-valMethod');
    if('req' === method && (el.value === null || el.value === '')){
           alert(el.getAttribute('data-message'));
           returnfalse;
    }
} 
</script></head><body><formname="myForm"action="#"onsubmit="return validateForm(this)"method="post">
First name: 
    <inputdata-message="First name must be filled out"data-valMethod="req"onchange="return valEl(this)"; name="fname"><br /><inputtype="submit"value="Submit"></form></body></html>​​​​​​​​​​​​​​​​​​​

I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element. Since HTML5 the Data-* attributes are very handy for these things :-) This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.

From here you can expand the valEl-function to accommodate other types of validation. Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.

Happy coding. /G

PS http://jsfiddle.net/ePPnn/11/ for sample code

Post a Comment for "Validate A Form Using Javascript"