DIV CSS 佈局教程網

jQuery 表單驗證實戰:會員資料、密碼修改與卡號查詢
編輯:關於JavaScript     

表單驗證的標準套路是:每個欄位配一個檢查函式,用旗標記錄「這個欄位目前是否合法」,focus/blur 時即時回饋,送出前再總檢一遍。以下依場景拆解。

旗標宣告

var realnameFlag = 0, addressFlag = 0, zipFlag = 0;
var cellphoneFlag = 0, homephoneFlag = 0;
var oldpasswordFlag = 1, newpasswordFlag = 1;

0 代表通過,非 0 代表有問題,送出時只要檢查旗標即可,不必重跑所有驗證。

信箱

function check_email() {
  $("#showSpan").hide();
  var email = $.trim($("#email").val());
  if (email == null || email == "") {
    emailFlag = 1;
    $("#emailMsg").html("<span class='tips'>請輸入郵箱信息</span>");
    return;
  }
  // 以「半形算 1、全形算 2」的方式估算視覺長度
  if (email.replace(/[^\x00-\xff]/g, "**").length <= 4 ||
      email.replace(/[^\x00-\xff]/g, "**").length >= 50) {
    $("#emailMsg").html("<span class='tips'>郵箱長度不正確</span>");
    emailFlag = 1; return;
  }
  var reg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
  if (reg.test(email)) { $("#emailMsg").html(""); emailFlag = 0; }
  else {
    $("#emailMsg").html("<span class='tips'>郵箱格式不正確</span>");
    emailFlag = 1;
  }
}

replace(/[^\x00-\xff]/g, "**") 是個好用的小技巧:把每個非 ASCII 字元換成兩個字元,就能用 length 估算「中文算兩個字寬」的視覺長度。

真實姓名

function check_realname() {
  $("#showSpan").hide();
  var realname = $.trim($("#realname").val());
  var tip = "<span class='tips'>請輸入真實姓名,20個英文或10個漢字</span>";
  if (realname == null || realname == "") { $("#realnameMsg").html(tip); realnameFlag = 1; return; }
  if (realname.indexOf("··") != -1) { $("#realnameMsg").html(tip); realnameFlag = 1; return; }
  // 姓名前後不能是「·」
  if (realname.substring(0, 1) == "·" || realname.substring(realname.length - 1) == "·") {
    $("#realnameMsg").html(tip); realnameFlag = 1; return;
  }
  var reg = new RegExp("^([a-zA-Z]|[\\u4E00-\\u9FFF])+$", "g");
  if (!reg.test(realname)) { $("#realnameMsg").html(tip); realnameFlag = 1; return; }
  var len = realname.replace(/[^\x00-\xff]/g, "**").length;
  if (len >= 4 && len <= 20) { realnameFlag = 0; $("#realnameMsg").html(""); }
  else { $("#realnameMsg").html(tip); realnameFlag = 1; }
}

用 \u4E00-\u9FFF 限定中文區段,再擋掉「·」出現在首尾或連續出現,是中文姓名欄位常見的組合檢核。

手機與市話

function check_cellphone() {
  $("#showSpan").hide();
  var cellphone = $.trim($("#cellphone").val());
  while (true) {                       // 去掉前綴 0
    if (cellphone.substring(0, 1) == "0") { cellphone = cellphone.substring(1); }
    else { break; }
  }
  $("#cellphone").val(cellphone);
  if (cellphone == null || cellphone == "") {
    $("#cellphoneMsg").html("<span class='tips'>請輸入移動電話號碼</span>");
    cellphoneFlag = 1; return;
  }
  var re = /^1{1}[3,4,5,8]{1}\d{9}$/;
  if (!re.test(cellphone)) {
    cellphoneFlag = 1;
    $("#cellphoneMsg").html("<span class='tips'>請輸入正確的移動電話號碼</span>");
  } else { cellphoneFlag = 0; $("#cellphoneMsg").html(""); }
}

function check_homephone() {
  $("#showSpan").hide();
  var homephone = $.trim($("#homephone").val());
  if (homephone == null || homephone == "") { homephoneFlag = 0; $("#homephoneMsg").html(""); return; }
  var re = /(^((\d{3,4}-)?\d{7,8})$)|(^1{1}[3,4,5,8]{1}\d{9}$)/;
  if (!re.test(homephone)) {
    homephoneFlag = 1;
    $("#homephoneMsg").html("<span class='tips'>請正確輸入電話號碼,格式為:000-00000000</span>");
  } else { homephoneFlag = 0; $("#homephoneMsg").html(""); }
}

市話允許留空(非必填),填了才驗格式,這在實務上很常見。

地址與郵遞區號

function check_address() {
  var address = $.trim($("#address").val());
  if (address == null || address == "") {
    $("#addressMsg").html("<span class='tips'>請輸入詳細地址</span>"); addressFlag = 1;
  } else if (address.replace(/[^\x00-\xff]/g, "**").length > 120) {
    addressFlag = 1; $("#addressMsg").html("<span class='tips'>長度超長</span>");
  } else { addressFlag = 0; $("#addressMsg").html(""); }
}

function check_zip() {
  var zip = $.trim($("#zip").val());
  var re = /^[0-9]+$/;
  if (zip.length != 0 && (!re.test(zip) || zip.length != 6)) {
    zipFlag = 1;
    $("#zipMsg").html("<span class='tips'>請輸入郵政編碼,由6位數字組成</span>");
  } else { zipFlag = 0; $("#zipMsg").html(""); }
}

密碼三連:舊密碼、新密碼、確認新密碼

function check_oldPassword() {
  $("#msgSpan").html(""); $("#newpsMsg").html(""); $("#repsMsg").html("");
  var oldPS = $.trim($("#oldPassword").val());
  if (oldPS == null || oldPS == "") {
    oldpasswordFlag = 1;
    $("#oldpsMsg").html("<span class='tips'>請輸入舊密碼</span>");
    return false;
  }
  if (!/^.{6,16}$/.test(oldPS)) {
    oldpasswordFlag = 1;
    $("#oldpsMsg").html("<span class='tips'>舊密碼輸入長度不正確</span>");
    return false;
  }
  oldpasswordFlag = 0; $("#oldpsMsg").html("");
}

function check_newPassword() {
  $("#oldpsMsg").html(""); $("#repsMsg").html(""); $("#msgSpan").html("");
  $("#repeatPassword").val("");                  // 新密碼一改,清空確認欄
  var newPS = $.trim($("#newPassword").val());
  if (newPS == null || newPS == "") {
    newpasswordFlag = 1;
    $("#newpsMsg").html("<span class='tips'>請輸入新密碼,由6-16位字符組成</span>");
    return false;
  }
  var len = newPS.replace(/[^\x00-\xff]/g, "**").length;
  if (len < 6 || len > 16) {
    newpasswordFlag = 1;
    $("#newpsMsg").html("<span class='tips'>新密碼長度不正確</span>");
    return false;
  }
  newpasswordFlag = 0; $("#newpsMsg").html("");
}

function check_repeatPassword() {
  $("#oldpsMsg").html(""); $("#newpsMsg").html(""); $("#msgSpan").html("");
  if ($("#repeatPassword").val() == null || $.trim($("#repeatPassword").val()) == "") {
    $("#repsMsg").html("<span class='tips'>請輸入重復新密碼</span>");
    newpasswordFlag = 1; return false;
  } else if ($.trim($("#repeatPassword").val()) != $.trim($("#newPassword").val())) {
    newpasswordFlag = 1;
    $("#repsMsg").html("<span class='tips'>兩次密碼輸入的不一致!</span>");
    return false;
  }
  newpasswordFlag = 0; $("#repsMsg").html("");
}

卡號查詢:卡號、密碼、驗證碼

function check_cardNum() {
  var cardnum = $.trim($("#cardNum").val());
  if (cardnum == null || cardnum == "") {
    $("#numMsg").html("<span class='tips'>請輸入卡號</span>"); cardnumFlag = 1; return false;
  }
  $("#numMsg").html(""); cardnumFlag = 0;
}
function check_passWord() {
  var password = $.trim($("#passWord").val());
  if (password == null || password == "") {
    passwordFlag = 1; $("#psMsg").html("<span class='tips'>請輸入密碼</span>"); return false;
  }
  passwordFlag = 0; $("#psMsg").html("");
}
function check_vcode() {
  var vcode = $.trim($("#vcode").val());
  if (vcode == null || vcode == "") {
    vcodeFlag = 1; $("#vcodeMsg").html("<span class='tips'>請輸入驗證碼</span>"); return false;
  }
  if (!/^[0-9]*$/.test(vcode)) {
    vcodeFlag = 1; $("#vcodeMsg").html("<span class='tips'>請正確輸入驗證碼</span>"); return false;
  }
  vcodeFlag = 0; $("#vcodeMsg").html("");
}

事件綁定

$(document).ready(function () {
  // 會員資料
  $("#email").focus(function () { check_email(); });
  $("#email").blur(function ()  { check_email(); });

  $("#realname").focus(function () { check_realname(); });
  $("#realname").blur(function ()  { check_realname(); });

  $("#cellphone").focus(function () { check_cellphone(); });
  $("#cellphone").blur(function ()  { check_cellphone(); });

  $("#homephone").focus(function () { check_homephone(); });
  $("#homephone").blur(function ()  { check_homephone(); });

  $("#address").focus(function () { check_address(); });
  $("#address").blur(function ()  { check_address(); });

  $("#zip").focus(function () { check_zip(); });
  $("#zip").blur(function ()  { check_zip(); });

  // 三級聯動:縣市 → 市 → 區
  $("#province").change(function () {
    $.post("_jquery", { type: "getProvince", province: $(this).val() }, function (msg) {
      $("#city").html(msg); $("#region").html("");
    });
  });
  $("#city").change(function () {
    $.post("_jquery", { type: "getCity", city: $(this).val() }, function (msg) {
      $("#region").html(msg);
    });
  });

  // 密碼修改
  $("#oldPassword").focus(function ()    { check_oldPassword(); });
  $("#oldPassword").blur(function ()     { check_oldPassword(); });
  $("#newPassword").focus(function ()    { check_newPassword(); });
  $("#newPassword").blur(function ()     { check_newPassword(); });
  $("#repeatPassword").focus(function () { check_repeatPassword(); });
  $("#repeatPassword").blur(function ()  { check_repeatPassword(); });

  // 卡查詢
  $("#cardNum").focus(function () { check_cardNum(); });
  $("#cardNum").blur(function ()  { check_cardNum(); });
  $("#passWord").focus(function () { check_passWord(); });
  $("#passWord").blur(function ()  { check_passWord(); });
  $("#vcode").focus(function ()   { check_vcode(); });
  $("#vcode").blur(function ()    { check_vcode(); });

  // 取消原因:限制 65 字
  $("#cancelreason").bind('input propertychange', function () {
    var maxLength = 65;
    if ($(this).val().length > maxLength) { $(this).val($(this).val().substring(0, maxLength)); }
    return false;
  });
});

送出前總檢

function formsubmit() {
  $("#showSpan").hide();
  // 先清掉舊提示
  $("#emailMsg").html(""); $("#realnameMsg").html(""); $("#cellphoneMsg").html("");
  $("#homephoneMsg").html(""); $("#addressMsg").html(""); $("#zipMsg").html("");

  if (emailFlag != 0 || $("#email").val() == null || $("#email").val() == "") { $("#email").focus(); return; }
  if (realnameFlag != 0 || $("#realname").val() == null) { $("#realname").focus(); return; }
  if ($("input[name=sex]:checked").val() == null) { alert("請選擇性別"); $("#sex").focus(); return; }
  if (cellphoneFlag != 0) { $("#cellphone").focus(); return; }
  if (homephoneFlag != 0) { $("#homephone").focus(); return; }

  var province = $("#province").val(), city = $("#city").val(), region = $("#region").val();
  if (province == "" || city == "" || region == "" ||
      province == null || city == null || region == null) {
    $("#szcode").html("<span class='tips'>請選擇地區</span>"); return;
  }
  if (addressFlag != 0 || $("#address").val() == "") { $("#address").focus(); return; }
  if (zipFlag != 0) { $("#zip").focus(); return; }

  $("#myform").submit();
}

function psformSubmit() {
  $("#oldpsMsg").html(""); $("#newpsMsg").html(""); $("#repsMsg").html("");
  var oldps = $.trim($("#oldPassword").val());
  var newps = $.trim($("#newPassword").val());
  var reps  = $.trim($("#repeatPassword").val());
  if (oldpasswordFlag != 0 || oldps == "") { $("#oldPassword").focus(); return; }
  if (newpasswordFlag != 0 || newps == "") { $("#newPassword").focus(); return; }
  if (newpasswordFlag != 0 || reps == "" || reps != newps) { $("#repeatPassword").focus(); return; }
  $("#psform").submit();
}

// 表單重置:清空提示並還原縣市區
function formreset() {
  $("#showSpan").hide();
  document.forms["myform"].reset();
  $("#emailMsg").html(""); $("#realnameMsg").html(""); $("#cellphoneMsg").html("");
  $("#homephoneMsg").html(""); $("#addressMsg").html(""); $("#zipMsg").html(""); $("#szcode").html("");
  $("#province").html($("#hprovince").val());
  $("#city").html($("#hcity").val());
  $("#region").html($("#hregion").val());
}

// 換驗證碼圖片:靠 query string 打斷快取
function dochange() {
  $("#vcodeImg").fadeOut('fast', function () {
    $(this).attr('src', '_verifycode?ver=' + new Date().getMilliseconds())
           .delay(200).fadeIn('slow');
  });
}

整套模式的優點是「每個欄位自己管好自己」:驗證函式純粹、可獨立測試,送出時只讀旗標不重算。要再優化,可以把重複的 focus/blur 綁定抽成一個迴圈,用陣列驅動,程式碼還能再少一半。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved