如何在失去焦点时立即验证字段

时间:2021-05-12 22:17:41

I am learning web development. And I have a login form where I have two text field one for email and one for password. I want to have validation for email field. Currently, I am able to validate but it occurs when I click on submit button. Is there an way I can do the validation as soon as the email field loses focus. I want to call validateEmail method as soon as focus loses.

我正在学习网络开发。我有一个登录表单,其中有两个文本字段用于电子邮件,一个用于密码。我想要验证电子邮件字段。目前,我能够验证但是当我点击提交按钮时会发生。有一种方法,一旦电子邮件字段失去焦点,我就可以进行验证。我想在焦点丢失时立即调用validateEmail方法。

This is what I have till now:

这就是我现在所拥有的:

HTML File

<div id="ErrMsg" style="color:red">
    <form id="myForm" action = "" method="post">
        <input id="email" name="Email" type="email" class="form-control" placeholder="Email">
        <input id="pass" name="Password" type="password" class="form-control" placeholder="Password" />
        <button id="signIn" type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
    </form>

JS File

window.loginView = Backbone.View.extend({
        events: {
            'click #signIn': 'doSignIn',
        },
        initialize: function() {
            console.log('Initializing Login View');
        },
        validateEmail: function(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);
        },
        doSignIn: function(event) {
            $("#ErrMsg").text("");
            var email = $("#email").val();
            // checking if email is valid
            if (!this.validateEmail(email)) {
                $("#ErrMsg").text(email + " is not valid :(");
            }
            else
            {
            // some logic to fetch data from REST
            }
        }

2 个解决方案

#1


1  

Yes, there is a way. You can bind an focusout event.

是的,有办法。您可以绑定焦点事件。

EDIT: add another event (after 'click #signIn': 'doSignIn'):

编辑:添加另一个事件(在'click #signIn':'doSignIn'之后):

'focusout #signIn': 'doSignIn'

#2


1  

As you are using jquery see this https://api.jquery.com/blur/

当您使用jquery时,请参阅https://api.jquery.com/blur/

$("#email").blur(validateEmail)

(obviously this requires a function named validateEmail)

(显然这需要一个名为validateEmail的函数)

#1


1  

Yes, there is a way. You can bind an focusout event.

是的,有办法。您可以绑定焦点事件。

EDIT: add another event (after 'click #signIn': 'doSignIn'):

编辑:添加另一个事件(在'click #signIn':'doSignIn'之后):

'focusout #signIn': 'doSignIn'

#2


1  

As you are using jquery see this https://api.jquery.com/blur/

当您使用jquery时,请参阅https://api.jquery.com/blur/

$("#email").blur(validateEmail)

(obviously this requires a function named validateEmail)

(显然这需要一个名为validateEmail的函数)