Reputation: 2634
I've added onfocus and onblur to my text input of a form.
<form id='AddCameraFormWebcam' name='' method='post' action='<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>'>
<label for="CameraName">Camera name: </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>
This now breaks my validation I had with 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!")
}
}
});
});
Someone can now submit without typing anything for the camera name because Enter label for camera
will get submitted to the server. How can I still show an error?
Upvotes: 3
Views: 3753
Reputation: 12544
The easiest way is to create a custom rule (you already have a 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!"
}
}
});
A jsfiddle based on your form here: http://jsfiddle.net/bSQQx/2/
Upvotes: 1