Rachel
Rachel

Reputation: 1159

Live validation using javascript

Html:

    <div id="error" style="position:absolute; left:auto; top:7px;"></div>
    <div style="position:absolute; left:auto; top:25px;">
    First name: <input type="text" id="fname" name="fname"><br>
    Last name: <input type="text" id="lname" name="lname"><br>
    <input type="submit" value="Submit" onclick="requiredFields()"><div>

Javascript:

function requiredFields(){
    var fName = document.getElementById("fname").value;
    var lName = document.getElementById("lname").value;
    if(fName == ""){
        document.getElementById("error").innerHTML = "First name field cannot be empty";
    }else if(lName == ""){
        document.getElementById("error").innerHTML = "Last name field cannot be empty";
    }else{
        document.getElementById("error").innerHTML = "";
        alert("successful");
    }
}

just check my link and help me.. http://jsfiddle.net/GACKm/

Upvotes: 0

Views: 2242

Answers (5)

Jared Farrish
Jared Farrish

Reputation: 49208

Here's an approach that uses some approaches that are more modern than inline event handlers (e.g., onchange=""). This is driven by data- attributes, as you will see, and although it is not currently configured to handle anything other than an input[type=text] right now, it could be expanded to work with selects, textareas, etc.

What is below makes no pretenses to work with IE8 and lower, due to those versions using attachEvent instead of addEventListener to setup the event handlers. Again, this could be worked in, but it does work in all other modern browsers. It should work in IE9, although that is untested.

It may look like a lot going on, but take a look at it and see if you can work out how it operates. Feel free to ask me any questions you like, as well.

Here is a fiddle (tested in Chrome and Firefox):

http://jsfiddle.net/ndXTb/

HTML

<aside>
    <ol id="errors"></ol>
</aside>
<section id="signup">
    <form action="#">
        <p>
            <label for="fname">First Name:</label>
            <span>
                <input type="text" id="fname" name="fname" class="required" 
                       data-validate-error="First name may not be empty."
                       data-error-sort="0"/>
            </span>
        </p>
        <p>
            <label for="lname">Last name:</label>
            <span>
                <input type="text" id="lname" name="lname" class="required" 
                       data-validate-error="Last name may not be empty."
                       data-error-sort="1"/>
            </span>
        </p>
        <p>
            <label for="addr1">Address 1:</label>
            <span>
                <input type="text" id="addr1" name="addr1" class="required" 
                       data-validate-error="Address may not be empty."
                       data-error-sort="2"/>
            </span>
        </p>
        <p>
            <label for="addr2">Address 2:</label>
            <span><input type="text" id="addr2" name="addr2"/></span>
        </p>
        <p>
            <label for="city">City:</label>
            <span>
                <input type="text" id="city" name="city" class="required" 
                       data-validate-error="City may not be empty."
                       data-error-sort="3"/>
            </span>
        </p>
        <p>
            <label for="state">State:</label>
            <span>
                <input type="text" id="state" name="state" class="required" 
                       data-validate-error="State may not be empty."
                       data-error-sort="4"/>
            </span>
        </p>
        <p>
            <span></span>
            <span style="text-align: right;">
                <input type="submit" value="Submit"/>
            </span>
        </p>
    </form>
</section>

CSS

#signup {
    display: table;
}
#signup form > p {
    display: table-row;
}
#signup p > label,
#signup p > span {
    display: table-cell;
    font-weight: bold;
    padding: 5px;
}
#signup p > label {
    text-align: right;
    width: 150px;
}
.validationerror input {
    border: 1px solid #a00;
    background-color: #ffd;
    padding: 2px 1px;
}
.validationerror:after {
    content: '!';
}

Javascript

window.addEventListener('load', function init(){
    var signup = document.getElementById('signup'),
        fields = signup.getElementsByClassName('required'),
        errors = document.getElementById('errors'),
        error = '<li>{error}</li>',
        submitted = false,
        errorlog = [],
        index = 0,
        field,
        focusin;

    signup.addEventListener('submit', validateform);

    while (field = fields[index++]) {
        field.addEventListener('blur', validatefield);
        field.addEventListener('keyup', validatefield);
    }

    function validatefield() {
        var message = this.dataset['validateError'],
            sort = this.dataset['errorSort'],
            parent = this.parentNode;

        if (this.value === '' && (message && sort)) {
            errorlog[sort] = error.replace('{error}', message);
            parent.className += ' validationerror';

            if (!focusin) {
                focusin = this;
            }
        } else if (this.value !== '' && (message && sort)) {
            delete errorlog[sort];

            parent.className = parent.className.replace('validationerror', '');

            if (focusin == this) {
                focusin = null;
            }
        }

        if (!submitted) {
            isvalid();
        }
    }

    function validateform(event) {
        index = 0;
        errorlog = [];
        focusin = null;

        submitted = true;

        while (field = fields[index++]) {
            callevt(field, 'focus');
            callevt(field, 'blur');
        }

        submitted = false;

        if (!isvalid()) {
            if (focusin) {
                focusin.focus();
            }

            focusin = null;

            event.preventDefault();
            return false;
        }
    }

    function isvalid() {
        errors.innerHTML = '';

        if (errorlog.length) {
            errors.innerHTML = errorlog.join('');

            return false;
        }

        return true;
    }

    function callevt(el, type) {
        var evt = document.createEvent('HTMLEvents');

        evt.initEvent(type, true, true);
        el.dispatchEvent(evt);
    }
});

Upvotes: 1

DayTimeCoder
DayTimeCoder

Reputation: 4332

Here is the jsFiddle

//Javascript

<script type="text/javascript" language="javascript">
    var oneTimeMsgClikced = false;
    function requiredFields() {
        var fName = document.getElementById("fname").value;
        var lName = document.getElementById("lname").value;
        if (fName == "") {
            document.getElementById("error").innerHTML = "First name field cannot be empty";
            oneTimeMsgClikced = false;
        } else if (lName == "") {
            document.getElementById("error").innerHTML = "Last name field cannot be empty";
            oneTimeMsgClikced = false;
        } else {
            document.getElementById("error").innerHTML = "";
            if (oneTimeMsgClikced == false) {
                alert("successful");
                oneTimeMsgClikced = true;
            }
        }
    }
</script>

//html code

<body>
    <div id="error" style="position: absolute; left: auto; top: 7px;">
        Errors here
    </div>
    <div style="position: absolute; left: auto; top: 25px;">
        First name:
        <input type="text" id="fname" name="fname" onblur="requiredFields()" />
        <br />
        Last name:
        <input type="text" id="lname" name="lname" onblur="requiredFields()"/>
        <br />
        <input type="submit" value="Submit" onclick="requiredFields()" />
    </div>
</body>

Upvotes: 1

Kabir
Kabir

Reputation: 2156

you can try this:

<script>
function checkFName()
{
    fName = document.getElementById("fname").value;
    if(fName == ""){
        document.getElementById("error").innerHTML = "First name field cannot be empty";
        document.getElementById("fname").focus;
        return false;
    }
}

function checkLName()
{
    lname = document.getElementById("lname").value;
    if(lname == ""){
        document.getElementById("error").innerHTML = "Last name field cannot be empty";
        document.getElementById("lname").focus;
        return false;
    }
}
</script>


<div id="error" style="position:absolute; left:auto; top:7px;"></div>
    <div style="position:absolute; left:auto; top:25px;">
    First name: <input type="text" id="fname" name="fname" onchange="checkFName();"><br>
    Last name: <input type="text" id="lname" name="lname" onchange="checkLName();"><br>
    <input type="submit" value="Submit"><div>

Hope this will help

Upvotes: 0

Bazinga777
Bazinga777

Reputation: 5281

You should not use onclick event handler for Submit.

For live validation you can use onblur, insert it into the input box. This will validate the input every time you move away from the input field.

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

You can try with onBlur and onKeyUp

Upvotes: 0

Related Questions