看板 Ajax 關於我們 聯絡資訊
小弟我靠著W3S自學javascript 遇到問題 但週遭卻苦無同好可以討論 希望前輩們能給予指點或提示 有段程式我不太明白它的意思,程式取自以下網址 http://www.w3school.com.cn/js/js_form_validation.asp 紅色部分是我看不懂的地方,先謝過各位前輩 <(_ _)> <html> <head> <script type="text/javascript"> function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@") dotpos=value.lastIndexOf(".") if (apos<1||dotpos-apos<2) {alert(alerttxt);return false} else {return true} } } function validate_form(thisform) { with (thisform) { if (validate_email(email,"Not a valid e-mail address!")==false) {email.focus();return false} } } </script> </head> <body> <form action="submitpage.htm"onsubmit="return validate_form(this);" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 117.19.225.158 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1459184453.A.230.html
weiclin: apos是"@"的位置, 如果email不含@,或是@在第一個字 03/29 03:35
weiclin: 那apos會小於1, dotpos也是類似,只是找到最後一個"."位置 03/29 03:36
weiclin: 如果"@"跟最後一個"."的距離小於2表示有問題 03/29 03:37
weiclin: 簡單說就是在檢查 email 的格式啦 03/29 03:39
weiclin: 如果格式錯誤,就使用 email.focus()讓游標停在email欄位 03/29 03:39
謝謝你, W大
mmis1000: 不過這種事,javascript裡有更簡單的regex,一般人不會 03/30 00:52
mmis1000: 這樣做。 03/30 00:52
mmis1000: 這段code,拿regex就是 /@.+\./.match(email) 而已 03/30 00:53
也謝謝m大的建議 ※ 編輯: alfven (49.217.50.248), 03/31/2016 01:32:22