使用javascript进行实时验证

时间:2013-03-07 06:22:27

标签: javascript button

  • 我在这里有一个文本框验证。错误消息不会作为警报发出,而是会打印在html div标签中。

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");
    }
}
  • 点击按钮,打印错误信息。
  • 我的问题是,javascript中是否有实时验证?
  • 我的意思是,首先应该出现错误信息,点击按钮,然后用户在文本框中输入值,如果名字文本框有任何值,我需要清除错误信息而不再点击按钮

只需查看我的链接并帮助我.. http://jsfiddle.net/GACKm/

5 个答案:

答案 0 :(得分:1)

以下是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代码

<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>

答案 1 :(得分:1)

这是一种使用比内联事件处理程序更现代的方法(例如onchange="")的方法。这是由data-属性驱动的,正如您将看到的那样,虽然它目前尚未配置为处理input[type=text]以外的任何内容,但它可以扩展为与select一起使用,textarea等等。

以下内容不适用于IE8及更低版本,因为这些版本使用attachEvent而不是addEventListener来设置事件处理程序。同样,这可以使用,但它确实适用于所有其他现代浏览器。它应该在IE9中工作,虽然这是未经测试的。

它可能看起来很多,但看看它,看看你是否可以弄清楚它是如何运作的。请随意问我喜欢的任何问题。

这是一个小提琴(在Chrome和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);
    }
});

答案 2 :(得分:0)

您可以尝试使用onBluronKeyUp

答案 3 :(得分:0)

您不应该使用onclick事件处理程序进行提交。

对于实时验证,您可以使用onblur,将其插入输入框。这将在您每次离开输入字段时验证输入。

答案 4 :(得分:0)

你可以试试这个:

<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>

希望这会有所帮助