需求說明:
前端頁面使用正則表達式驗證輸入的數據為正整數。
代碼說明:
這里只介紹正則表達式,其他部分的代碼不做介紹。如果有其他需要自行修改即可。
步驟一:建立一個頁面可以是html、jsp等,引入jquery-3.2.1.min.js(其他版本亦可)。
步驟二:編寫正則表達式。
代碼部分如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-3.2.1.min.js" ></script> </head> <body> </body> <script> //這里默認頁面加載時驗證輸入數據 $(function () { var value="-123456789012"; if(isPInt(value)){ console.log("參數:符合驗證要求"); }else{ console.log("參數: 不符合驗證要求"); } }) //正整數驗證 function isPInt(str) { var g = /^[1-9]*[1-9][0-9]*$/; return g.test(str); } </script> </html>