jQuery检查输入.val()是否包含某些字符 [英] Jquery check if input .val() contains certain characters
问题描述
我需要检查页面上的输入字段是否包含字符.
I need to check if an input field on my page contains characters.
这是用于非常基本的电子邮件地址验证,因此我只想检查文本是否为空,并且包含@
和.
字符.
This is for very basic email address validation so I only want to check if the text is not empty, and contains @
and .
characters.
我一直在尝试这种方式:
I've been trying this way:
if (($("." + parentname.attr("class") + " #email").val().contains("@")) && ($("." + parentname.attr("class") + " #email").val().contains(".")))
{
email = 1;
}
假定值为me@this.com
,此代码将引发以下错误:
Assuming a value of me@this.com
, this code will throw the following error:
对象me@this.com没有方法包含"
Object me@this.com has no method 'contains'
因此,我进行了一些研究,发现.contains适用于DOM对象,而不是建议使用此字符串的字符串:
So I did some research and found that .contains is for DOM objects, not strings with a suggestion to try this:
if (($("." + parentname.attr("class") + " #email").val().IndexOf("@") != -1) && ($("." + parentname.attr("class") + " #email").val().IndexOf(".") != -1))
{
email = 1;
}
会导致类似的错误:
对象me@this.com没有方法'IndexOf'
Object me@this.com has no method 'IndexOf'
我在这里基本上没有主意,特别是考虑到以下代码可以在我创建的另一个站点中正常运行:
I'm basically out of ideas here especially considering that the following code works as I want it to in another site I've made:
if ($("#contact-email").val().contains("yahoo.com")) {
$(".errmsg").text("Domain yahoo.com has been banned due to excessive spam, please use another domain.");
}
有人可以建议我尝试做其他事情吗?或者,更好的方法是如何正确地做到这一点?
Can anyone suggest any other things I could try or, better yet, how to do this properly?
推荐答案
indexOf
开始时不使用大写字母 I .尝试以下方法:
indexOf
does not use a capital I at the start. Try this instead:
if (($("." + parentname.attr("class") + " #email").val().indexOf("@") != -1) && ($("." + parentname.attr("class") + " #email").val().indexOf(".") != -1))
{
email = 1;
}
这篇关于jQuery检查输入.val()是否包含某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!