简体   繁体   中英

Uncaught TypeError: Cannot call method 'contains' of undefined

NOTE Please see this question for a bit of background...

So my (very basic) form validation is working - sort of.

When checking the input value for the email address field, I want to make sure that the email address has a value (ie is not blank) and contains @ and . characters so I did this...

<div width="100%" class="con1">

    <div class="lable">
        <label for="email">Email Address *</label>
    </div>
    <input  type="text" name="email" class="span4">

</div>

<script>

$('input[type=submit]').click(function() {
    var parentname = $(this).parent('div');
    console.log('Form used: ' + parentname);

    var email = 0,

    // Validate email
    if ($('.' + parentname.attr('class') + ' #email').val() == '')
    {
        alert('Please enter a valid email address');
    }
    else
    {
        if (($('.' + parentname.attr('class') + ' #email').val().contains('@')) && ($('.' + parentname.attr('class') + ' #email').val().contains('.')))
        {
            email = 1;
        }
        else
        {
            alert('Please enter a valid email address');
        }
    }
});
</script>

It looks a little weird but complexity as mentioned in the linked question above required me to think a little differently with my selectors.

Basically $('.' + parentname.attr('class') + ' #email') is the same as writing (in the case I'm using $('.con1 #email') as the selector which I believe to be correct based on my HTML structure.

I tried working with $('.' + parentname.attr('class').child('#email') but then kept getting an error that said the element had no method 'child'

I wrote this based on a previous form I'd created where I'd used the same principle in effect, to block emails coming from yahoo.com because I was getting a lot of spam from there:

if ($("#contact-email").val().contains("yahoo.com")) {
     $(".errmsg").text("Domain yahoo.com has been banned due to excessive spam, please use another domain.");
}
else
{
    email = 1;
}

While the 2nd sample that I've pasted here works, the first one that validates the email field more thoroughly keeps returning this error:

Uncaught TypeError: Cannot call method 'contains' of undefined

I can't understand how this could work in one site and not another. I feel like I'm missing something so would appreciate it if anyone can see what that might be.

Thanks in advance!

元素应具有id="email"以允许选择器:

$('.' + parentname.attr('class') + ' #email')

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