[英]What JavaScript functions exist that I can use to check that an email and phone # are valid without resorting to a jquery plugin?
在表格上,我需要確保所有字段均已填寫,並且電話號碼和 email 地址有效。 我嘗試使用 jQuery 驗證插件,但它改變了頁面的外觀。 該插件還在某些出乎意料的地方動態地尋找一些 css 文件。
我喜歡 jQuery 但插件對於我想要的來說似乎太多了。
由於我需要做的就是確保字段不為空並且電話號碼有效並且 email 有效,您建議使用哪些 javascript 功能? 我仍將使用 jQuery 內核。
服務器端我們想使用 apache commons PhoneNumberFormatter 和 email 驗證相同。
謝謝!
我認為您正在尋找JavaScript 正則表達式,使用作為 JavaScript 標准部分的 RegExp object。 您可以使用它對 email 地址和電話號碼進行基本檢查。
例如
function emailIsValid(emailAddress) {
var emailRegex = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/;
return !!emailAddress.match(emailRegex);
}
上面的代碼沒有經過測試,但它應該讓你知道如何去做。 只需對電話號碼再次執行相同操作,然后執行以下操作:
if (emailIsValid(emailAddressValue) && telephoneNumberIsValid(telephoneValue)) {
//Submit form
} else {
alert ("There are errors on the form, please correct and invalid data");
}
在這個 jsfiddle 中,您將找到我用來檢查表單字段的 JQueryless 方法。 它使用間隔 function 定期檢查所有表單字段。
每個人都專注於 email 和電話號碼驗證,但如果您需要幫助來檢測空文本框,甚至只是如何/何時調用代碼以進行電子郵件/電話驗證:
<script type="text/javascript">
function validate()
{
var curVal;
for(var index = 1 ; index < 15 ; index++)
{
curVal = document.getElementById("textbox_"+index).value
if(curVal == "")
{
alert("empty text box")
return(false); //false will stop the form from submitting
}
if(index = 5)// email text box
{
//validate email
}
}
}
</script>
<type="input" id="textbox_1">
<type="submit" value="Submit" onClick="validate()">
這是 email 的一個
function checkemail()
{
var str=email
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z] {2})?)$/i
if (filter.test(str))
testresults=true
else
{
alert("Please input a valid email address!")
testresults=false
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.