简体   繁体   English

JavaScript-如果电子邮件错误,则设置类

[英]JavaScript - set class if e-mail is wrong

I've been blinded last 40 minutes trying to find why this isn't working. 最近40分钟,我一直瞎了眼,试图找出为什么这行不通。

So, I have this function to check if e-mail is valid or not 因此,我具有此功能来检查电子邮件是否有效

checkEmail: function () { // CHECK IF E-MAIL IS WRONG OR NOT
    var check = /^[\w\.\+-]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,6}$/;
    if (!check.test(this.options.email.get('value'))) {
        return false
    }
    return true
},

Works well! 效果很好!

Now, I need to set a error class to style the input, during validation. 现在,我需要在验证期间设置一个error类来设置输入的样式。 For that I used this: 为此,我使用了这个:

var s_email = this.options.email.get('value');
if ((s_email == '') || (s_email == this.options.email_text) || (s_email == 'Give me your e-mail') || (!checkEmail())) { // CHECK AND STYLE E-MAIL INPUT FORM
            this.options.email.set("class", "error")
        } else {
            this.options.email.set("class", "success")
        } 

But doesn't work, always give me error even if a valid email was there. 但是不起作用,即使有有效的电子邮件,也总是给我error

One issue is that checkEmail() is being called without a context object (value of this ): 一个问题是在没有上下文对象( this值)的情况下调用checkEmail() ):

if (... || (!checkEmail())) {

But, it expects to have one with a particular structure: 但是,它期望具有一种特殊的结构:

if (!check.test(this.options.email.get('value'))) {
//              ^^^^

The value of this is determined when a function is called rather than how it's defined. this当确定function被调用,而不是它是如何定义的。 But, you can use .call(thisArg) to specify its value, allowing you to pass along the current context object. 但是,您可以使用.call(thisArg)指定其值,从而允许您传递当前的上下文对象。

if (... || (!checkEmail.call(this))) {

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

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