Check if input field contains @ character?

2019-09-21 09:32发布

Im trying to check if my input field contains an @ sign in it

so here is what i have and its not working:

$( "#Button" ).click(function() {
    if ($('#email:contains("@")')) {

    } else { 
        $('#email').text('Wrong');
    }
});

http://jsfiddle.net/xJtAV/70/

Any ideas?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-21 10:02

:contains() returns a jQuery object matching the criteria. It does not match value.

Use indexOf() over .val(),

if ($('#email').val().indexOf('@') > -1) {

Also, in your else{}, use .val() as text() does not set any value.

$('#email').val('Wrong');

But I'd suggest you use another element say <span id="emailError">

Updated Fiddle

查看更多
别忘想泡老子
3楼-- · 2019-09-21 10:08

Try this: http://jsfiddle.net/xJtAV/71/. The string function indexOf() will search any string for whatever you'd like and return the index of the first character of the first occurence...

String indexOf() docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

JS

$( "#Button" ).click(function() {

    if ($('#email').val().indexOf('@') >= 0) {
       $('#email').val('Yes! It contains an "@" symbol!');
    } else { 
        $('#email').val('No :( No "@" symbol');
    }

});

HTML

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input id="email" name="email" class="email" type="text" />
<br><br>

<div id="Button" style="height:100px; width: 150px; background-color: #000;">
</div>
查看更多
登录 后发表回答