简体   繁体   中英

JavaScript - set class if e-mail is wrong

I've been blinded last 40 minutes trying to find why this isn't working.

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

One issue is that checkEmail() is being called without a context object (value of this ):

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. But, you can use .call(thisArg) to specify its value, allowing you to pass along the current context object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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