0

我编写了一个自定义方法来验证价格是否有效。例如。没有字母等。因此我写了一个自定义方法。但我不知道如何传递价值。

方法:

function checkIsPriceValid(input)
{

   alert(input);
    return false;
}

表单验证

$(function () { 
jQuery.validator.addMethod("checkIsPriceValid", function (value, element) {
  return checkIsPriceValid();
  //check whether checkbox dist and algo is checked
}, "Invalid number");  


$("#addProductForm").validate({
  errorPlacement: function (error, element) {
    //error.appendTo(element.prev());
    error.insertAfter(element);
  },
  rules: { 


productName: { 
  required: true

},
productCategory:{ 
  required: true

},
productDescription: {
    required: true
},
productOrginalPrice:{
    required: true,
    checkIsPriceValid: this.val()
}
4

2 回答 2

0

您在 中使用的名称addMethod是完全任意的,不必匹配表单中的任何内容。

首先需要将至少一个参数传递给checkIsPriceValid方法内的调用。我正在使用value,因为那是你想要测试的。

jQuery.validator.addMethod("checkIsPriceValid", function (value, element) {
  return checkIsPriceValid(value);
  //check whether checkbox dist and algo is checked
}, "Invalid number");

function checkIsPriceValid(value){
    return value /* some test*/ ? true :false;

}

然后在validate.rules对象中通过添加方法名称来使用该方法,但分配值的true方式与您使用的其他规则相同,例如“必需”

productOrginalPrice:{
    required: true,
    checkIsPriceValid: true
}

演示http://jsfiddle.net/mpFz3/

于 2012-06-17T16:37:26.383 回答
0

编辑 - 对不起,我对第一个参数有误(仍然不完全确定它的确切用途)。我从未使用过该插件,但看看这是否有效:

$(function () { 
jQuery.validator.addMethod("checkIsPriceValid", function (value, element) {
  return checkIsPriceValid(value, element);
  //check whether checkbox dist and algo is checked
}, "Invalid number");  

那你应该有

function checkIsPriceValid(value, element)
{

    alert(value);
    return false;
}

对于您的验证方法:

$("#addProductForm").validate({
 ...
productOrginalPrice:{
    required: true,
    checkIsPriceValid: "Price is invalid"
}

虽然我没有使用过这个插件,只是看看文档和其他例子,这个插件有一个非常丑陋的 API。JQuery Tools 验证器是更好的 IMO。

于 2012-06-17T16:22:32.583 回答