-1

This is my form:

jsFiddle of my FORM

function formValidator(){
var a = document.getElementById('uname');
var b = document.getElementById('m_photo');
var c= document.getElementById('fname');
var d= document.getElementById('lname');
var e= document.getElementById('p_add');
var f= document.getElementById('c_add');
var g= document.getElementById('b_add');
var h= document.getElementById('country');
var i= document.getElementById('state');
var j= document.getElementById('city');
var k= document.getElementById('pcode');
var l= document.getElementById('id_proof');
var m= document.getElementById('quali_proof');
var n= document.getElementById('p_addproof');
var o= document.getElementById('c_addproof');
var p= document.getElementById('resume');
var q= document.getElementById('dob');
var r= document.getElementById('mobile');
var s= document.getElementById('email');
var t= document.getElementById('quali');
var u= document.getElementById('dsgn');
var v= document.getElementById('rep_person');
var w= document.getElementById('join');
var x= document.getElementById('p_hist');
var y= document.getElementById('sh_des');
var z= document.getElementById('app_by');
var A= document.getElementById('accept');

// Check each input in the order that it appears in the form!
if(lengthRestriction(a, 6, 8)){
    if(""==b.value)
        {alert("Please Upload the Member Photo");
            if(isAlphabet(c, "Please enter only Alphabets for First Name")){
                if(isAlphabet(d, "Please enter only Alphabets for Last Name")){
                    if(e==null || e=="")
                        {alert("Please Enter your Permanent Address");
                            if(f==null || f=="")
                                {alert("Please Enter your Current Address");
                                    if(g==null || g=="")
                                        {alert("Please Enter your Branch Address");
                                            if(h==null || h=="")
                                                {alert("Please Enter the Country Name");
                                                    if(i==null || i=="")
                                                        {alert("Please Enter the State Name");
                                                            if(j==null || j=="")
                                                                {alert("Please Enter the City Name");

    //if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
            if(isNumeric(k, "Please enter a valid 6 digit Pin Code")){
                if(l==null || l=="")
                    {alert("Please Upload the Id-Proof");
                        if(m==null || m=="")
                            {alert("Please Upload the Qualification Proof");
                                if(n==null || n=="")
                                    {alert("Please Upload the Permanent Address Proof");
                                        if(o==null || o=="")
                                            {alert("Please Upload the Current Address Proof");
                                                if(p==null || p=="")
                                                    {alert("Please Upload the Resume");
                                                        if(q==null || q=="")
                                                            {alert("Please Upload the D.O.B Proof");
                                                                if(lengthRestriction(r,10,10)){
                                                                    if(emailValidator(s, "Please enter a valid email address")){
                                                                        if(t==null || t=="")
                                                                            {alert("Please Enter the Qualification Details");
                                                                                if(madeSelection(u, "Please Choose a Designation")){
                                                                                    if(v==null || v=="")
                                                                                        {alert("Please Enter the name of the Reporting Person");
                                                                                            if(w==null || w=="")
                                                                                                {alert("Please Enter the Joining Date");
                                                                                                    if(x==null || x=="")
                                                                                                        {alert("Please Write Something about Past History");
                                                                                                            if(y==null || y=="")
                                                                                                                {alert("Please give some Description about the Member");
                                                                                                                    if(z==null || z=="")
                                                                                                                        {alert("Empty Field: APPOINTED BY");
                                                                                                                            if(madeSelection(A, "Please Accept the terms and conditions")){
                                                                                            return true;
                                                                    }}
                                                                }}
                                                            }}
                                                        }}
                                                    }}
                                                }}
                                            }}
                                        }}
                                    }}
                                }}
                            }}
                        }}
                    }}
                }

return false;


}
 function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
    alert(helperMsg);
    elem.focus(); // set the focus to this input
    return false;
}
return true;
}

function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
    return true;
}else{
    alert(helperMsg);
    elem.focus();
    return false;
}
}

function isAlphabet(elem, helperMsg){
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
    return true;
}else{
    alert(helperMsg);
    elem.focus();
    return false;
}
}

function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
    return true;
}else{
    alert(helperMsg);
    elem.focus();
    return false;
}
}

function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
    return true;
}else{
    alert("Please enter between " +min+ " and " +max+ " characters");
    elem.focus();
    return false;
}
}

function madeSelection(elem, helperMsg){
if(elem.value == "Select Designation"){
    alert(helperMsg);
    elem.focus();
    return false;
}else
    {
    return true;
}
}

function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
    return true;
}else{
    alert(helperMsg);
    elem.focus();
    return false;
}
}

Here the validation takes place for the first two cases only. I am unable to figure out the problem. Can any one help?

I am required to validate the current field before the user move to the next field, so all the if statement were nested to follow the specific order.

Also, I wish to redirect the form data to another file. I used action="abc.html"(its an eg.). When the submit button is clicked it directly goes to abc.html instead of validating the form data.

Sparky
  • 98,165
  • 25
  • 199
  • 285

2 Answers2

1
if(lengthRestriction(a, 6, 8)){
    if(""==b.value)
        {alert("Please Upload the Member Photo");
            if(isAlphabet(c, "Please enter only Alphabets for First Name")){

You have some functions (such as lengthRestriction and isAlphabet shown above) that return true if the field is valid. However, your inline logic (like with b above) resolves to false if the field is valid. I suggest that you write a "not empty" function (or alternatively change the logic in your if statement) so that the if is true if the field is valid.

As a suggestion, I acknowledged that I don't know how much control you have over the project; have you considered using a javascript library such as jquery? You might benefit from using code that other people have already written and tested.

Aaron Kurtzhals
  • 2,036
  • 3
  • 17
  • 21
1

OK. You should really organize that :)

Alterante Approach

Since you have this kind of a long form; you can:

  • Mark necessary fields as required with a class name.
  • Use HTML5 custom data- attributes to assign the validation logic and the corresponding error message for each field.

For example:

<input id="fname" type="text" class="required" data-validation="alphanumeric"
        data-error="Please enter your first name." />

<input id="age" type="text" class="required" data-validation="numeric"
    data-error="Please enter your age." />

<input id="accept" type="checkbox" class="required" data-validation="check" 
    data-error="Please accept the terms of agreement." />

Then;

  • Get those "marked-as-required" fields in a loop.
  • Validate them by using the attached logic.
  • Either show all the gathered error messages at the end or process and break one-by-one (as you do).

For example:

function validateForm() {
    // get the .required fields as NodeList
    var requiredElems = document.getElementsByClassName('required') || 
                            document.querySelectorAll('.required');
    // validate fields one-by-one
    for (var i = 0; i < requiredElems.length; i++) {
        var elem = requiredElems[i];
        if (validateField(elem) === false) {
            alert(elem.getAttribute('data-error')); //get the error message from the custom data attribute and alert.
            elem.focus();
            return false; //break;
        }
    }
    return true;
}

function validateField(elem) {
    var rxp, valid = true,
        // get the validation type from the custom data attribute.
        validationType = elem.getAttribute('data-validation');
    // all validation logic in one place
    switch (validationType) {
        case 'alphanumeric':
            rxp = /^[0-9a-zA-Z]+$/;
            valid = rxp.test(elem.value);
            break;
        case 'numeric':
            rxp = /^[0-9]+$/;
            valid = rxp.test(elem.value);
            break;
        case 'email':
            rxp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
            valid = rxp.test(elem.value);
            break;
        case 'check':
            valid = elem.type == 'checkbox' ? elem.checked : true;
            break;
    }
    
    return valid;
}

There is two more benefits to this;

  • You can add extra form fields without needing to change your javascript. Just insert the element in your HTML with the .required class, data-validation and data-error attributes.
  • You can add extra validation logic by just adding another case in the validateField() method.

HTML5 Form Validation

We could also use proper HTML5 Form Validation; such as using the required attribute instead of a custom .required class (to identify required fields in-line). There are lots of other useful features, such as new input types (email, number, url, etc), placeholder text, autofocus fields. But unfortunately, these are not fully supported by most versions of major browsers yet.

The 'data-' attribute, on the other hand; is at least usable, including IE6 (even if it is not really recognized by old browsers). That's why, I think the approach above is more browser-friendly at this time.

For more information on HTML5 Forms, see this page.

Anyway, this is just to demonstrate how you should structure/organize your flow. There should be much more logical approaches than this one but at least, this should give you an idea.

Note: If you consider this approach, don't forget to change your DOCTYPE accordingly.

Community
  • 1
  • 1
Onur Yıldırım
  • 32,327
  • 12
  • 84
  • 98