Javascript实时验证 [英] Javascript live validation

查看:69
本文介绍了Javascript实时验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的HTML / JavaScript表单,我正在为作业而努力,但我希望它能够验证输入为用户类型(我的验证出现在文本字段的下面)我做到了?我的代码如下:

I have a very simple HTML/JavaScript form that I am working on for coursework, I have got it to work however i would like it to validate the input as the user types (my validation appears below the text field) how can I achieve this? My code is as follows:

<!DOCTYPE html>
<html>
<head>
    <script class="jsbin" src="http:ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">  </script>
    <meta charset=utf-8 />
    <title>Email Validation</title>
</head>
<body>
    <form onsubmit='validate(); return false;'>
        <p>Enter an email address:</p>
        <input id='email' placeholder="example@example.com" size="21">
        <button type='submit' id='validate'>Submit</button>
    </form>
    <br />
    <h2 id='result'></h2>
    <script>
        function validateEmail(email) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
        }
        function validate() {
            $("#result").text("");
            var email = $("#email").val();
            if (validateEmail(email)) {
                $("#result").text(email + " is valid");
                $("#result").css("color", "green");
            } else {
                $("#result").text(email + " is not valid");
                $("#result").css("color", "red");
            }
            return false;
        }
        $("form").bind("submit", validate);
    </script>
</body>
</html>


推荐答案

对于不使用jQuery的方法,感兴趣的,这里有另一个堆栈溢出问题:关于输入更改事件

For methods not using jQuery, in case you're interested, there's another Stack Overflow question here: On Input Change Event.

有许多方法可以完成您想要的任务,但在这种情况下,您可以执行如下操作:

There are many ways to do what you want listed there, but in this case you could do something like this:

var input = document.querySelector('input');

input.addEventListener('input', function()
{
    // Check input.value for what you're looking for here
});

请参阅 jsFiddle Drew Noakes 在其他页面中为例。

See the jsFiddle that Drew Noakes' made in that other page for an example.

但是,由于您使用的是jQuery,因此Nicholas Kyriakides的建议是最好的选择。

But, since you're using jQuery, then Nicholas Kyriakides's suggestion is the way to go.

这篇关于Javascript实时验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆