- 在 JavaScript Function 中動態添加驗證
/**
* 設置隱藏域 限制前兩位數字
*/
function setProductNo() {
var $value = $("#product option:selected").attr("preNo");
$value = $value ? $value : "";
$("#preNo").val($value);
$("#labelProduct").html("軟件號前兩位:" + $value);
jQuery.validator.addMethod("checkPreNo",function(value,element,params) {
// 未設定產品值,直接跳過驗證
if (!$value) {
return true;
}
if (value.length > 2) {
if ($value == value.substring(0, 2)) {
return true;
}
} else {
if ($value == value) {
return true;
}
}
return false;
},$.validator.format("<span style='color:red'>軟件號前兩位必須是"+ $value +" </span>"));
}
頁面上的 html 片段如下
<select name="product" id="product" onchange="setProductNo();">
<option value="">請選擇</option>
</select>
<label for="product" id="labelProduct"></label>
- 在 Ajax 回調中直接加入驗證,用普通的 rules 可能加載不上驗證,需要使用 setTimeout 延遲加載
$.ajax({
url: "getJsonCustomerUpgradeProduct.do",
cache:false,
type: "post",
async: false,
dataType: "json",
data: param,
success: function(data){
console.log(JSON.stringify(data))
if (data.success=='true') {
var items = data.items;
var content = "<option value=\"\">請選擇</option>";
for (var i = 0;items && i < items.length; i++) {
var item = items[i];
content += "<option id='"+ item.id +"' >" + item.name + "</option>"
}
$("#" + param.htmlId).html(content);
$("#" + param.htmlId).select2();
if (data.showUpgradePruduct) {
$("#"+param.rowId).show();
setTimeout(function() {
$("#upgradeProduct").rules("add", {required: true});
}, 0);
$("#"+param.showStopAccount).hide();
} else {
$("#"+param.rowId).hide();
setTimeout(function() {
$("#upgradeProduct").rules("remove", "required");
}, 0);
}
}
}
})