3

我在表单的文本输入中添加了 onfocus 和 onblur。

<form id='AddCameraFormWebcam' name='' method='post' action='<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>'>
    <label for="CameraName">Camera name:&nbsp;</label>
    <input id="CameraName" name="camera_name" size="24" maxlength="36" value="Enter label for camera" onfocus="if(this.value==this.defaultValue){this.value=''; this.style.color='#000';};" onblur="if(this.value==''){this.value=this.defaultValue; this.style.color='#666';}" />
...
    <button type='submit' class='submit_camera' name='addcamera' value='Add'>Add</button>

</form>

现在这打破了我对 jquery 的验证:

$(".submit_camera").click(function() {
    $("#AddCameraFormWebcam").validate({
        rules: {
            camera_name: {
                required: true,
                cameravalidation: true,
                minlength: 3,
                maxlength: 32
            }
        },
        messages: {
            camera_name: {
                required: "Enter a label for your camera",
                minlength: jQuery.format("At least {0} characters required!"),
                maxlength: jQuery.format("Maximum {0} characters allowed!")
            }
        }
    });
});

有人现在可以在不为相机名称输入任何内容的情况下提交,因为Enter label for camera将被提交到服务器。我怎样才能仍然显示错误?

4

1 回答 1

1

最简单的方法是创建自定义规则(您已经有相机验证?):

var enterText =  $("#CameraName")[0].defaultValue; // "Enter label for camera";

jQuery.validator.addMethod("cameravalidation", function(value, element) {
    return value != enterText && value.length > 0;
}, "Enter a label for your camera");

$("#AddCameraFormWebcam").validate({
        rules: {
            camera_name: {
                cameravalidation: true,
                minlength: 3,
                maxlength: 32
            }
        },
        messages: {
            camera_name: {
                minlength: "At least 3 characters required!",
                maxlength: "Maximum 32 characters allowed!"
            }
        }
    });

基于您的表单的 jsfiddle:http: //jsfiddle.net/bSQQx/2/

于 2012-06-25T19:19:56.723 回答