首页 文章

如果value为0,则Jquery formvalidation必填字段

提问于
浏览
0

我目前有jquery表单验证插入到我的页面,我目前有一个问题,试图验证状态下拉列表,如何构建视图是这样的 . 用户选择国家,然后激活回控制器并返回链接到该国家/地区的状态并构建状态下拉列表 . 在选择一个国家之前,状态下拉列表的选择值为0,其中的文本是“请选择一个状态”,我的理解Jquery表单验证将看到0并假设它是一个值,而在我的情况下,这不是一个值我需要用户选择更大的值0.所以当用户按下提交时,如果状态选择值为0,我需要显示错误信息否则继续 . 这是我现在所拥有的

$('#myForm').validate({ // initialize the plugin
    rules: {
        "UserDetails.SelectedCountry": "required",
        "UserDetails.SelectedState": {
            required: function (element) {
                var value = $("#UserDetails_SelectedState").val() == 0;

                if (value) { // If the value is true I need to return false to make it required
                    alert("here");
                    return false;
                } else { // Otherwise value is greater then 0 ok to carry on,
                    return true;
                }

            }
        }
        "UserDetails.Postcode": "required"
    },
    messages: {
        "UserDetails.SelectedCountry": "Please choose your country",
        "UserDetails.SelectedState": "Please choose your state",
        "UserDetails.Postcode": "Please enter your postcode",
    }
});

请有人能告诉/展示如何验证0 .

更新

我今天一直在和这个打开和关闭,你可以从我的jquery标记中看到,如果它是真的我然后返回false我看到警告消息“here”但是字段没有突出显示为红色,也没有错误消息“请选择你的状态“显示,那里有人可能会有什么东西?

1 回答

  • 0

    您可以将“请选择状态”值设置为=“”并禁用它 .

    像这样的东西

    <select>
      <option value="" disabled>Please Choose a State</option>
      <option value="1">1</option>
    </select>
    

    将您的验证更改为:

    var value = $("#UserDetails_SelectedState").val()
      if (value ==0 || value=="0") { // If the value is true I need to return false to make it required
                        alert("here");
                        return false;
                    } else { // Otherwise value is greater then 0 ok to carry on,
                        return true;
                    }
    

相关问题