html - javascript form validation with class - Stack Overflow

I've used the HTML5 form for a website. I thought, if I use HTML5, it automatically valid the form

I've used the HTML5 form for a website. I thought, if I use HTML5, it automatically valid the form. But, it won't properly for all the field at all the browser. So, I had to use javascript. As I ain't expert at javascript, I've to face lots of problems.

Here is the website

1)To show the error message, I create a div(div id="validation") beside the input field. I selected the div from javascript by document.getElementById. But, the input filed is not at one. There are many input field. So, I've to use that as class. Problem is there, I can't write the loop/code for document.getElementsByClassName at all.Basically, it's not wise for me to use class for that div#validation and use identical id for selecting by the javascript. Because, there can be same type of form in many number like this page. If anyone click the edit icon, there will be a popup form. So, I should use the div.validation not div#validation. I'm also afraid about the input id. At above link, there are same fielded input are stayed. So, if I target/select the input by id of the form from javascipt, it may not work where multiple form will be stayed. So, I can't understand what should I do. Recently, I've test one by one defining the div#validation and it worked.

(a) So, Please, write the code at least for two input filed targeting the class from javascript. So, I can put the javascript of remaining input field then. Screenshot of When I tested:











One thing that, I don't use "required" at anywhere as I'm using javascript. But, after trying and trying when, nothing is working, I've put "required" attribute at aleast at input field at HTML, javascript works! And without required filed at least at one input filed, javascript is not work! I don't understand why this happened. I don't want to use "required" any more.

(b) Also I want a red background when the filed is invalid like this: How can I do this with CSS or javascript?

Necessary HTML code:

<div class="wrapper">
        <header class="page_title">
            <h1>Create New Job</h1>
        </header>
        <section class="form">
            <form id="form" name="form" method="post" action="#">
                <label>Job ID:</label>
                <input type="text" name="job_id" id="job_id" placeholder="1">
                <div id="validation"></div>
                <label>Start Date:</label>
                <input type="text" name="start_date" id="start_date" placeholder="mm/dd/yy">
                <div id="validation"></div>
                <label>Deadline:</label>
                <input type="text" name="deadline" id="deadline" placeholder="mm/dd/yy">
                <div id="validation"></div>
                <label>Finish Date:</label>
                <input type="text" name="finish_date" id="finish_date" placeholder="mm/dd/yy">
                <div id="validation"></div>
                <label>Budget($):</label>
                <input type="text" name="budget" id="budget" placeholder="100">
                <div id="validation"></div>
                <label>Client ID:</label>
                <input type="text" name="client_id" id="client_id" placeholder="1">
                <div id="validation"></div>
                <label>Client Phone Number:</label>
                <input type="text" name="phone" id="phone" placeholder="01712333333">
                <div id="validation"></div>
                <label>Client Email address:</label>
                <input type="text" name="email" id="email" placeholder="[email protected]">
                <div id="validation"></div>
                <label>Bidder ID:</label>
                <input type="text" name="bidder_id" id="bidder_id" placeholder="1">
                <div id="validation"></div>
                <label>Number of Supervisor:</label>
                <select title="Supervisor" id="num_supervisor">
                        <option value="-1">Select</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                </select>
                <div id="validation"></div>
                <label>Odesk Profile Link:</label>
                <input type="text" name="odesk_link" id="odesk_link" placeholder="">
                <div id="validation"></div>
                <label>Owner Type:</label>
                <input type="radio" name="owner_type" id="owner_type" value="member" /><label class="text_label">Member</label>
                <input type="radio" name="owner_type" id="owner_type" value="employee" /><label class="text_label">Employee</label>
                <div id="validation"></div>
                <div class="clear"></div>
                <label>Message:</label> 
                <textarea id="message" name="message" rows="2" cols="20" placeholder="Your enquiry goes here"></textarea>
                <div id="validation"></div>
                <input type="submit" name="submit" id="submit" value="Submit" />
        </form>
     </section>
</div>

CSS:

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    border: 0 none;
    font-size: 100%;
    margin: 0;
    padding: 0;
    vertical-align: baseline;
}
a {
    text-decoration: none;
}

.clear { clear: both; }

article, aside, canvas, details, figcaption, figure, footer, header, hgroup, nav, menu, nav, section, summary {
    display: block;
}

h1 {
    font-size: 26px;    
}

body {
    background: #fff;
    font-family: sans-serif;
    color: #333;
    font-size: 12px;
    line-height: 1em;
}
.wrapper {
    width: 1000px;
    margin: 0 auto;
    position: relative;
    background: #fff;
}
header.page_title {
    background: #E3E3E3;
    border-radius: 7px 7px 7px 7px;
    color: #333;
    padding: 20px;
    margin: 40px 0 0 0; 
}
.form {
    width: 800px;
    margin: 20px 0 0 2px;
    border: none;
    background: #fff;
}
form {
    border: none;
    background: #fff;   
}

.form label { 
    display: block; 
    text-align: left; 
    width: 200px; 
    float:left; 
    margin: 5px 0 0 20px;
    font-size: 15px; 
}
.form label.text_label {
    width: auto;
    display: inline;
    margin: 5px 20px 15px 10px; 
}
.form input, .form select {
    float:left; 
    font-size:13px;
    margin: 0 0 10px 0; 
    padding: 0;
}
.form input:required {

}
input:valid {
    border: 1px solid #909090;

}
input[type=text]:invalid, input[type=date]:invalid, input[type=number]:invalid, input[type=email]:invalid, input[type=tel]:invalid, input[type=url]:invalid, textarea:invalid {
    border: 1px solid #FF0000;

}

.form input[type=text], .form input[type=date], .form input[type=number], .form input[type=email], .form input[type=tel], .form input[type=url] { 
    width: 500px; 
    height: 27px;
    border: 1px solid #909090;
    border-radius: 3px; 
}
.form input[type=file] {
    width: 500px;   
}
.form select {
    width: 500px;
    height: 27px;
    line-height: 27px;
    padding: 3px 0 0 0;
    border: 1px solid #909090;
    border-radius: 3px; 
}
.form input[type="radio"] {
    margin: 5px 0 0 0;  
}
.form textarea { 
    float: left; 
    width: 500px; 
    height: 82px; 
    margin: 0 0 10px 0; 
    padding: 0; 
    font-size: 13px;
    border: 1px solid #909090; 
}
.form input[type="submit"] { 
    margin: 10px 0 20px 220px; 
    width: 100px; 
    height: 30px; 
    background: #FF6D1F; 
    text-align: center; 
    line-height: 30px; 
    color: #FFFFFF; 
    font-size: 13px; 
    font-weight: bold; 
    border: none;
    box-shadow: 0 1px 3px rgba(38, 151, 72, 0.5), 0 1px 0 #9FE662 inset; 
    border-radius: 5px;
    cursor: pointer;
}
.form input[type="submit"]:hover { 
    background: #FF822E;
}

input[type=text]:focus, textarea:focus, input[type=search]:focus, input[type=date]:focus, input[type=number]:focus, input[type=email]:focus, select:focus, input[type=tel]:focus, input[type=url]:focus {
    background: #fff;
    border-color: #595959;
    -webkit-box-shadow: 0px 0px 6px 0px rgba(103, 102, 106, .7);
    box-shadow: 0px 0px 6px 0px rgba(103, 102, 106, .7);
    outline: none;
}
#validation {
    background: #EAEAEA;
    width: 165px;
    height: 18px;
    /*opacity: .5;*/
    border: 1px solid #A69E7C;
    float: left;
    margin: -20px 0 0 -110px;
    padding: 7px 5px 10px 10px;
    border-radius: 0 0 7px 7px;
    box-shadow: 0 0 2px #888;
    color: #000;
    line-height: 14px;
    position: relative;
    display: none;
}
input[type=radio] #validation {
    margin-left: -10px; 
}
.arrow {
    width: 14px;
    height: 15px;
    position: absolute;
    background: url(../images/arrow-down.png) no-repeat;
    bottom: -15px;
    left: 77px;
    z-index: 120;   
}

Javascript:

var submit = document.getElementById("submit");
submit.onclick = function() {
    var job_id = document.getElementById("job_id").value;
    var validation = document.getElementById("validation");
    var form = document.getElementById("form");


    if(job_id == "") {
        validation.style.display = 'block';
        validation.innerHTML = "ID cannot be left empty";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
            validation.style.display = 'none';  
    }   

    var start_date = document.getElementById("start_date").value;
    if(start_date == "") {
        validation.innerHTML = "Please, Enter the date";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
            validation.style.display = 'none';  
    }

    var deadline = document.getElementById("deadline").value;
    if(deadline == "") {
        validation.innerHTML = "Please, Enter the deadline";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
            validation.style.display = 'none';  
    }

    var finish_date = document.getElementById("finish_date").value;
    if(finish_date == "") {
        validation.innerHTML = "Please, Enter the finish date";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';
    }

    var budget = document.getElementById("budget").value;
    if(isNaN(budget)) {
        validation.innerHTML = "Enter Numeric Value here.";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);

    }else if(budget == "") {
        validation.innerHTML = "Please, Enter the Budget";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
     }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
     }

     var client_id = document.getElementById("client_id").value;
     if(client_id == "") {
        validation.style.display = 'block';
        validation.innerHTML = "ID cannot be left empty";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var phone = document.getElementById("phone").value;
    if(isNaN(phone)) {
        validation.innerHTML = "Enter Numeric Value here.";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);

    }else if(phone == "") {
        validation.innerHTML = "Please, Enter the Phone number";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
     }else if(phone.length < 7) {
            validation.innerHTML = "Phone Number should be at least 7 chars";
            arrow = document.createElement("div");
            arrow.className = 'arrow';
            validation.appendChild(arrow);
     }else if(phone.length > 11) {
            validation.innerHTML = "Phone Number should be at best 11 chars";
            arrow = document.createElement("div");
            arrow.className = 'arrow';
            validation.appendChild(arrow);
     }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
     }

    var email = document.getElementById("email").value;
    var atpos=email.indexOf("@");
    var dotpos=email.lastIndexOf(".");
     if(email == "") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, enter email address";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
        validation.innerHTML = "This is not a valid email address";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }
    else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var bidder_id = document.getElementById("bidder_id").value;
     if(bidder_id == "") {
        validation.style.display = 'block';
        validation.innerHTML = "ID cannot be left empty";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var num_supervisor = document.getElementById("num_supervisor").value;
     if(num_supervisor == "-1") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, select";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var odesk_link = document.getElementById("odesk_id").value;
    var tomatch= /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
    if(odesk_link == "") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, Enter the url";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    } else if (tomatch.test(odesk_link)) {
        validation.innerHTML = "";
        validation.style.display = 'none';
        return true;
     }else {
        validation.style.display = 'block';
        validation.innerHTML = "This is not valid url";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);

        return false;
    }

     var owner_type = document.getElementById("owner_type").value;
     if(owner_type == "") {
        validation.style.display = 'block';
        validation.style.marginLeft = '0';
        validation.innerHTML = "Please, write something";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

     var message = document.getElementById("message").value;
     if(message == "") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, write something";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

}

(c)The javascript for radio button, url link and textarea input didn't show the correct error message. I think, code for that section is okay, but what's the problem, I don't understand.

I've used the HTML5 form for a website. I thought, if I use HTML5, it automatically valid the form. But, it won't properly for all the field at all the browser. So, I had to use javascript. As I ain't expert at javascript, I've to face lots of problems.

Here is the website

1)To show the error message, I create a div(div id="validation") beside the input field. I selected the div from javascript by document.getElementById. But, the input filed is not at one. There are many input field. So, I've to use that as class. Problem is there, I can't write the loop/code for document.getElementsByClassName at all.Basically, it's not wise for me to use class for that div#validation and use identical id for selecting by the javascript. Because, there can be same type of form in many number like this page. If anyone click the edit icon, there will be a popup form. So, I should use the div.validation not div#validation. I'm also afraid about the input id. At above link, there are same fielded input are stayed. So, if I target/select the input by id of the form from javascipt, it may not work where multiple form will be stayed. So, I can't understand what should I do. Recently, I've test one by one defining the div#validation and it worked.

(a) So, Please, write the code at least for two input filed targeting the class from javascript. So, I can put the javascript of remaining input field then. Screenshot of When I tested:











One thing that, I don't use "required" at anywhere as I'm using javascript. But, after trying and trying when, nothing is working, I've put "required" attribute at aleast at input field at HTML, javascript works! And without required filed at least at one input filed, javascript is not work! I don't understand why this happened. I don't want to use "required" any more.

(b) Also I want a red background when the filed is invalid like this: How can I do this with CSS or javascript?

Necessary HTML code:

<div class="wrapper">
        <header class="page_title">
            <h1>Create New Job</h1>
        </header>
        <section class="form">
            <form id="form" name="form" method="post" action="#">
                <label>Job ID:</label>
                <input type="text" name="job_id" id="job_id" placeholder="1">
                <div id="validation"></div>
                <label>Start Date:</label>
                <input type="text" name="start_date" id="start_date" placeholder="mm/dd/yy">
                <div id="validation"></div>
                <label>Deadline:</label>
                <input type="text" name="deadline" id="deadline" placeholder="mm/dd/yy">
                <div id="validation"></div>
                <label>Finish Date:</label>
                <input type="text" name="finish_date" id="finish_date" placeholder="mm/dd/yy">
                <div id="validation"></div>
                <label>Budget($):</label>
                <input type="text" name="budget" id="budget" placeholder="100">
                <div id="validation"></div>
                <label>Client ID:</label>
                <input type="text" name="client_id" id="client_id" placeholder="1">
                <div id="validation"></div>
                <label>Client Phone Number:</label>
                <input type="text" name="phone" id="phone" placeholder="01712333333">
                <div id="validation"></div>
                <label>Client Email address:</label>
                <input type="text" name="email" id="email" placeholder="[email protected]">
                <div id="validation"></div>
                <label>Bidder ID:</label>
                <input type="text" name="bidder_id" id="bidder_id" placeholder="1">
                <div id="validation"></div>
                <label>Number of Supervisor:</label>
                <select title="Supervisor" id="num_supervisor">
                        <option value="-1">Select</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                </select>
                <div id="validation"></div>
                <label>Odesk Profile Link:</label>
                <input type="text" name="odesk_link" id="odesk_link" placeholder="https://www.odesk./jobs/Frontend-engineer">
                <div id="validation"></div>
                <label>Owner Type:</label>
                <input type="radio" name="owner_type" id="owner_type" value="member" /><label class="text_label">Member</label>
                <input type="radio" name="owner_type" id="owner_type" value="employee" /><label class="text_label">Employee</label>
                <div id="validation"></div>
                <div class="clear"></div>
                <label>Message:</label> 
                <textarea id="message" name="message" rows="2" cols="20" placeholder="Your enquiry goes here"></textarea>
                <div id="validation"></div>
                <input type="submit" name="submit" id="submit" value="Submit" />
        </form>
     </section>
</div>

CSS:

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    border: 0 none;
    font-size: 100%;
    margin: 0;
    padding: 0;
    vertical-align: baseline;
}
a {
    text-decoration: none;
}

.clear { clear: both; }

article, aside, canvas, details, figcaption, figure, footer, header, hgroup, nav, menu, nav, section, summary {
    display: block;
}

h1 {
    font-size: 26px;    
}

body {
    background: #fff;
    font-family: sans-serif;
    color: #333;
    font-size: 12px;
    line-height: 1em;
}
.wrapper {
    width: 1000px;
    margin: 0 auto;
    position: relative;
    background: #fff;
}
header.page_title {
    background: #E3E3E3;
    border-radius: 7px 7px 7px 7px;
    color: #333;
    padding: 20px;
    margin: 40px 0 0 0; 
}
.form {
    width: 800px;
    margin: 20px 0 0 2px;
    border: none;
    background: #fff;
}
form {
    border: none;
    background: #fff;   
}

.form label { 
    display: block; 
    text-align: left; 
    width: 200px; 
    float:left; 
    margin: 5px 0 0 20px;
    font-size: 15px; 
}
.form label.text_label {
    width: auto;
    display: inline;
    margin: 5px 20px 15px 10px; 
}
.form input, .form select {
    float:left; 
    font-size:13px;
    margin: 0 0 10px 0; 
    padding: 0;
}
.form input:required {

}
input:valid {
    border: 1px solid #909090;

}
input[type=text]:invalid, input[type=date]:invalid, input[type=number]:invalid, input[type=email]:invalid, input[type=tel]:invalid, input[type=url]:invalid, textarea:invalid {
    border: 1px solid #FF0000;

}

.form input[type=text], .form input[type=date], .form input[type=number], .form input[type=email], .form input[type=tel], .form input[type=url] { 
    width: 500px; 
    height: 27px;
    border: 1px solid #909090;
    border-radius: 3px; 
}
.form input[type=file] {
    width: 500px;   
}
.form select {
    width: 500px;
    height: 27px;
    line-height: 27px;
    padding: 3px 0 0 0;
    border: 1px solid #909090;
    border-radius: 3px; 
}
.form input[type="radio"] {
    margin: 5px 0 0 0;  
}
.form textarea { 
    float: left; 
    width: 500px; 
    height: 82px; 
    margin: 0 0 10px 0; 
    padding: 0; 
    font-size: 13px;
    border: 1px solid #909090; 
}
.form input[type="submit"] { 
    margin: 10px 0 20px 220px; 
    width: 100px; 
    height: 30px; 
    background: #FF6D1F; 
    text-align: center; 
    line-height: 30px; 
    color: #FFFFFF; 
    font-size: 13px; 
    font-weight: bold; 
    border: none;
    box-shadow: 0 1px 3px rgba(38, 151, 72, 0.5), 0 1px 0 #9FE662 inset; 
    border-radius: 5px;
    cursor: pointer;
}
.form input[type="submit"]:hover { 
    background: #FF822E;
}

input[type=text]:focus, textarea:focus, input[type=search]:focus, input[type=date]:focus, input[type=number]:focus, input[type=email]:focus, select:focus, input[type=tel]:focus, input[type=url]:focus {
    background: #fff;
    border-color: #595959;
    -webkit-box-shadow: 0px 0px 6px 0px rgba(103, 102, 106, .7);
    box-shadow: 0px 0px 6px 0px rgba(103, 102, 106, .7);
    outline: none;
}
#validation {
    background: #EAEAEA;
    width: 165px;
    height: 18px;
    /*opacity: .5;*/
    border: 1px solid #A69E7C;
    float: left;
    margin: -20px 0 0 -110px;
    padding: 7px 5px 10px 10px;
    border-radius: 0 0 7px 7px;
    box-shadow: 0 0 2px #888;
    color: #000;
    line-height: 14px;
    position: relative;
    display: none;
}
input[type=radio] #validation {
    margin-left: -10px; 
}
.arrow {
    width: 14px;
    height: 15px;
    position: absolute;
    background: url(../images/arrow-down.png) no-repeat;
    bottom: -15px;
    left: 77px;
    z-index: 120;   
}

Javascript:

var submit = document.getElementById("submit");
submit.onclick = function() {
    var job_id = document.getElementById("job_id").value;
    var validation = document.getElementById("validation");
    var form = document.getElementById("form");


    if(job_id == "") {
        validation.style.display = 'block';
        validation.innerHTML = "ID cannot be left empty";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
            validation.style.display = 'none';  
    }   

    var start_date = document.getElementById("start_date").value;
    if(start_date == "") {
        validation.innerHTML = "Please, Enter the date";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
            validation.style.display = 'none';  
    }

    var deadline = document.getElementById("deadline").value;
    if(deadline == "") {
        validation.innerHTML = "Please, Enter the deadline";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
            validation.style.display = 'none';  
    }

    var finish_date = document.getElementById("finish_date").value;
    if(finish_date == "") {
        validation.innerHTML = "Please, Enter the finish date";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';
    }

    var budget = document.getElementById("budget").value;
    if(isNaN(budget)) {
        validation.innerHTML = "Enter Numeric Value here.";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);

    }else if(budget == "") {
        validation.innerHTML = "Please, Enter the Budget";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
     }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
     }

     var client_id = document.getElementById("client_id").value;
     if(client_id == "") {
        validation.style.display = 'block';
        validation.innerHTML = "ID cannot be left empty";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var phone = document.getElementById("phone").value;
    if(isNaN(phone)) {
        validation.innerHTML = "Enter Numeric Value here.";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);

    }else if(phone == "") {
        validation.innerHTML = "Please, Enter the Phone number";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
     }else if(phone.length < 7) {
            validation.innerHTML = "Phone Number should be at least 7 chars";
            arrow = document.createElement("div");
            arrow.className = 'arrow';
            validation.appendChild(arrow);
     }else if(phone.length > 11) {
            validation.innerHTML = "Phone Number should be at best 11 chars";
            arrow = document.createElement("div");
            arrow.className = 'arrow';
            validation.appendChild(arrow);
     }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
     }

    var email = document.getElementById("email").value;
    var atpos=email.indexOf("@");
    var dotpos=email.lastIndexOf(".");
     if(email == "") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, enter email address";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
        validation.innerHTML = "This is not a valid email address";
        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }
    else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var bidder_id = document.getElementById("bidder_id").value;
     if(bidder_id == "") {
        validation.style.display = 'block';
        validation.innerHTML = "ID cannot be left empty";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var num_supervisor = document.getElementById("num_supervisor").value;
     if(num_supervisor == "-1") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, select";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

    var odesk_link = document.getElementById("odesk_id").value;
    var tomatch= /^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
    if(odesk_link == "") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, Enter the url";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    } else if (tomatch.test(odesk_link)) {
        validation.innerHTML = "";
        validation.style.display = 'none';
        return true;
     }else {
        validation.style.display = 'block';
        validation.innerHTML = "This is not valid url";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);

        return false;
    }

     var owner_type = document.getElementById("owner_type").value;
     if(owner_type == "") {
        validation.style.display = 'block';
        validation.style.marginLeft = '0';
        validation.innerHTML = "Please, write something";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

     var message = document.getElementById("message").value;
     if(message == "") {
        validation.style.display = 'block';
        validation.innerHTML = "Please, write something";

        arrow = document.createElement("div");
        arrow.className = 'arrow';
        validation.appendChild(arrow);
    }else {
        validation.innerHTML = "";
        validation.style.display = 'none';  
    }

}

(c)The javascript for radio button, url link and textarea input didn't show the correct error message. I think, code for that section is okay, but what's the problem, I don't understand.

Share Improve this question edited May 9, 2013 at 21:48 user1896653 asked May 9, 2013 at 21:39 user1896653user1896653 3,34717 gold badges56 silver badges100 bronze badges 4
  • 4 Why do you have 20+ div's with the same ID? Why are you surprised document.getElementById doesn't work when it returns one element and you have 20+ elements with that particular ID? – dsgriffin Commented May 9, 2013 at 21:40
  • this is too bad page design and too bad validation code.. just use validate.js here – Mehmet Commented May 9, 2013 at 22:03
  • yes, I want to use the same Id's div as same class. And so, I want the code for document.gteElementsByClassName instead of document.getElementById which I've used now(document.getElementById). I can't write code/loop for gteElementsByClassName And for that reason, I've written the post – user1896653 Commented May 9, 2013 at 22:25
  • okay, may be it's hard for getting idea about my problem because of big post. Tomorrow, I'll write it again shortly with more clear. – user1896653 Commented May 9, 2013 at 23:17
Add a ment  | 

2 Answers 2

Reset to default 0

If you are okay with using jQuery as a js library, then here is a solution for you [for a) and b)]: http://jsfiddle/6fLNz/4/

Some ments:

  1. Never ever ever use one ID more than once.
  2. For javascript, you repeated the same code an awful lot of times; in that case you can make a kind of 'template function' with event handlers, so you don't have to retype the function everytime you want to launch it. Of course you will have to build specific functions for conditionals that don't evaluate with a !== or ===.
  3. I had a look at your project, and it really seems big enough to use jQuery or another JS library that might ease and speed up the development process.
  4. I put the input verification on .focusout event, so the user is immediatly notified of the error after he clicks/ shifts on another input. You can change line 22 input.on('focusout', function() to $('#submit').on('click', function() if you rather have the functions firing on click of the submit button.

jQuery function for reference:

$(document).ready(function() {
// First define user inputs
var inputs = [];
inputs[0] = $('#job_id');        // Job Id input
inputs[1] = $('#start_date');    // Start date input
inputs[2] = $('#deadline');      // Deadline input
// Add other inputs here like so => inputs[3] = $('#<input id>');

// Define the errors (error indexes must be the same as their inputs' indexes, eg errors[0] for inputs[0])
var errors = [];
errors[0]     = 'ID cannot be left empty';      // Job Id error
errors[1]     = 'Please enter the date';        // start date error
errors[2]     = 'Please enter the deadline';    // deadline error
// Add other errors here like so => errors[3] = $('#<input id>');

// These are the different validation patterns
var expressions = [];
expressions[0] = '';
expressions[1] = /regex/ ;

// Template function with event handlers
var showFormValidation = function showFormValidation(input, error, expression) {
    input.on('focusout', function() {
        if(input.val() == expression) {
            $(this).next('.validation').show();
            $(this).next('.validation').html(error);
            $(this).css({'box-shadow': '0 0 3px red',
                         '-moz-boxshadow': '0 0 3px red',
                        '-webkit-boxshadow': '0 0 3px red',
                         '-o-boxshadow': '0 0 3px red',
                         'border': '1px solid red'
                        });
        } else if(input.val() != expression) {
            $(this).next('.validation').hide();
            $(this).css({'box-shadow': 'none',
                         '-moz-boxshadow': 'none',
                        '-webkit-boxshadow': 'none',
                         '-o-boxshadow': 'none',
                         'border': '1px solid grey'
                        });
        }
    });
};
// This function will show the form validation for all input, if the input is == ''
for(i=0; i < errors.length; i++) { 
    showFormValidation( inputs[i], errors[i], expressions[0]);
}

});

I'm posting a new answer as this one is much more specific and sophisticated. However please read the bold note:

The code I have written here could almost be defined as a jQuery error validation plugin. Ultimately, for developing a polyvalent application which needs advanced errordisplay functions & others, you should really learn a javascript framework (like Ext.js, jQuery, jQuery UI[ a framework of a framework!], YUI, etc...) or master javascript to an at least advanced extent.

What the new function does:

  1. Check if input is empty [& display error]
  2. If input is not 1., check if input is shorter than given length [& display error]
  3. If input is not 2., check if input is longer than given length [& display error]
  4. If input is not 3., check if input has the specified string [& display error]
  5. If input is not 4., check if input has the specified regex pattern [& display error]
  6. If input passes all tests, error is hidden.

Now this es at a cost: For each function launch, you will have to specify 10 parameters, like this: function showFormValidation(input, errorBlank, minLength, errorminLength, maxLength, errormaxLength, find, errorFind, regex, errorRegex)

  • input is the input id from which to pare the value to
  • minLength and maxLength should be 2 integers (or null)
  • regex should be a // -enclosed regex pattern and find should be a string (eg. 'mail')
  • All parameters prefixed by 'error' are the errormessages to show when the preceding parameter is true (eg errorminLength will display if input is shorter than minLength)
  • If you don't want to test against certain values, set the parameters to null

For examples, look at the 3 last lines of the embedded code in this post.

Here is the new jQuery code (it is applied to the 3 first inputs of the fiddle here: http://jsfiddle/6fLNz/5/

$(document).ready(function() {
    // First define user inputs
    var inputs = [];
    inputs[0] = $('#job_id');        // Job Id input
    inputs[1] = $('#start_date');    // Start date input
    inputs[2] = $('#deadline');      // Deadline input
    // Add other inputs here like so => inputs[3] = $('#<input id>');

    // Define the errors (error indexes must be the same as their inputs' indexes, eg errors[0][0][0] for inputs[0])
    var errors = [];
    errors[0] = [];
    errors[1] = [];
    errors[2] = [];
    var blank = 0;
    var length = 1;
    var indexof = 2;
    // errors when input = empty
    errors[blank][0]     = 'ID cannot be left empty';      // Job Id error
    errors[blank][1]     = 'Please enter the date';        // start date error
    errors[blank][2]     = 'Please enter the deadline';    // deadline error
    errors[blank][3]     = 'You haven\'nt chosen an ownertype'; // ownertype radiobutton error
    // errors when not enough chars or too many chars
    errors[length][0]    = 'Your message must be at least x characters in length.';
    errors[length][1]    = 'Your message must be at most x characters in length.';
    // errors when input doesn't contain a certain string
    errors[indexof][0]   = 'Your message doesn\'t contain the necessary characters';

    // Template function with event handlers
    var showFormValidation = function showFormValidation(input, errorBlank, minLength, errorminLength, maxLength, errormaxLength, find, errorFind, regex, errorRegex) {

        input.on('focusout', function() {
            var errorVisible = function errorVisible(error) {
                if(error !== null) {
                input.next('.validation').show();
                input.next('.validation').html(error);
                input.css({'box-shadow': '0 0 3px red',
                            '-moz-boxshadow': '0 0 3px red',
                            '-webkit-boxshadow': '0 0 3px red',
                            '-o-boxshadow': '0 0 3px red',
                            'border': '1px solid red'
                            });
                }
            };
            var errorHidden = function errorHidden() {
            input.next('.validation').hide();
                    input.css({'box-shadow': 'none',
                                 '-moz-boxshadow': 'none',
                                '-webkit-boxshadow': 'none',
                                 '-o-boxshadow': 'none',
                                 'border': '1px solid grey'
                                });
            };
            if(input.val() == '') {                                                     // shows error if input is empty
                errorVisible(errorBlank);
            } else if(input.val() != '') {
                errorHidden();
                if(input.val().length < minLength && minLength != null) {               // shows error if input is shorter than 'minLength' characters
                    errorVisible(errorminLength);
                } else if(input.val().length >= minLength || minLength == null) {
                    errorHidden();
                    if(input.val().length > maxLength && maxLength != null) {           // shows error if input is longer than 'maxLength' characters
                        errorVisible(errormaxLength);
                    } else if (input.val().length <= maxLength || maxLength == null) {
                        errorHidden();
                        if(input.val().indexOf(find) == -1 && find != null) {           // shows error if string 'find' is not found in the input.val()
                            errorVisible(errorFind);
                        } else if(input.val().indexOf(find) != -1 || find == null) {
                            errorHidden();
                            if(!input.val().match(regex) && regex != null) {            // shows error if string doesn't follow a certain regex pattern
                                errorVisible(errorRegex);
                            } else if(input.val().match(regex) || regex == null) {
                                errorHidden();
                            }
                        };
                    };
                };
            };
        });
    };


    showFormValidation(inputs[0], errors[blank][0], 4, errors[length][0], null, null, 'mailto', errors[indexof][0], null, null );
    showFormValidation(inputs[1], errors[blank][1], 6, errors[length][0], 6, errors[length][1], null, null, null, null );
    showFormValidation(inputs[2], errors[blank][2], null, null, null, null, null, null, /\//i, 'wrong regex');
});

I chose the put the error messages collectively in arrays, but you can also enter the strings directly as function parameters.

Cheers.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745286286a4620582.html

相关推荐

  • html - javascript form validation with class - Stack Overflow

    I've used the HTML5 form for a website. I thought, if I use HTML5, it automatically valid the form

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信