简体   繁体   English

使用javascript进行实时验证

[英]Live validation using javascript

  • I have a text box validation here. 我在这里有一个文本框验证。 The error message will not come as an alert, instead it will get printed in the html div tag. 错误消息不会作为警报,而是将打印在html div标签中。

Html: 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: 使用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");
    }
}
  • On click of a button, am printing the error message. 单击按钮,打印错误消息。
  • My question is, is there any live validation in javascript? 我的问题是,javascript中有任何实时验证吗?
  • I mean, at first the error message should come at, button on click, and the time user enters value into text box, if first name text box has any value, i need to clear the error message without clicking the button again. 我的意思是,首先应该出现错误信息,点击按钮,然后用户在文本框中输入值,如果名字文本框有任何值,我需要清除错误信息而不再点击按钮。

just check my link and help me.. http://jsfiddle.net/GACKm/ 只需查看我的链接并帮助我.. http://jsfiddle.net/GACKm/

Here is the jsFiddle 这是jsFiddle

//Javascript //使用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 // 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>

Here's an approach that uses some approaches that are more modern than inline event handlers (eg, onchange="" ). 这是一种使用比内联事件处理程序更现代的方法的方法(例如, 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 select s, textarea s, etc. 正如您将看到的,这是由data-属性驱动的,虽然它目前没有配置为处理input[type=text]以外的任何内容,但它可以扩展为使用select s, textarea等。

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. 由于这些版本使用attachEvent而不是addEventListener来设置事件处理程序,因此下面的内容不会使用IE8及更低版本。 Again, this could be worked in, but it does work in all other modern browsers. 同样,这可以使用,但它确实适用于所有其他现代浏览器。 It should work in IE9, although that is untested. 它应该在IE9中工作,尽管这是未经测试的。

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): 这是一个小提琴(在Chrome和Firefox中测试):

http://jsfiddle.net/ndXTb/ http://jsfiddle.net/ndXTb/

HTML 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 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 使用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);
    }
});

您可以尝试使用onBluronKeyUp

You should not use onclick event handler for Submit. 您不应该使用onclick事件处理程序进行提交。

For live validation you can use onblur, insert it into the input box. 对于实时验证,您可以使用onblur,将其插入输入框。 This will validate the input every time you move away from the input field. 这将在您每次离开输入字段时验证输入。

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 希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM