2012-06-25 71 views
3

我已經添加onfocus和onblur到我的文本輸入的窗體。jQuery與onblur驗證/ onfocus

<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會得到提交到服務器。我怎麼能仍然顯示一個錯誤?

+0

調用點擊事件中驗證之前,你可以嘗試檢查輸入字段並將其清除,如果它等於默認值。或者,您也可以爲驗證器編寫自己的自定義規則。 –

回答

1

最簡單的方法是創建一個自定義規則(你已經有了一個cameravalidation?):根據您的形式在這裏

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/

+0

對,已經有一個自定義規則,添加了你的建議。謝謝! – Tom