So I have a multipart form that has fields for text, integers and file uploads.
I can use dataAnnotations and validationMessageFor for the text and int fields, but not for the file upload.
So I implemneted the following code to validate the file uploads:
$(document).ready(function() {
$("#Error").hide();
var pdfFile = '<%=Model.PdfFile %>';
if (pdfFile == null || pdfFile1 == "") {
$("#Submit").click(function() {
var ext = $('#File').val().split('.').pop().toLowerCase();
var file = $('#File').val();
if ((!file || ext != 'pdf')) {
$('#Error').show();
return false;
}
return true;
});
}
});
This code works great, as far as I can tell at this point, but it executes before the checks on the other fields, so it looks sloppy.
In other words, if the user has multiple errors on the form when they click submit,
The validation message for the file upload appears, but not for the other fields.
If the user then uploads a valid file and clicks submit again, then the validation messages for the other fields appear. Sloppy.
So I tried implementing jQuery validation for the textboxes as well, but for some reason this doesn’t work:
$(document).ready(function () {
$("#captionVal").hide();
$("#Submit").click(function () {
var caption = $("#Caption").val();
if (!caption || caption == "") {
$("#captionVal").show();
return false;
}
return true;
});
});
It seems it always reads the field as null, so it never returns true.
I tried adding
$("Caption").change(function() {
as well as
$("#Caption").bind(function() {
in front of the if statement, but to no avail.
I also tried using the jQuery validation with
$(document).ready(function () {
$("#term").validate();
});
But that did nothing at all (perhaps I just don’t understand how to use the plugin?)
So my question is, how can I validate the textboxes?
Really all I need to do is make sure they are not empty, and if they are display an error label (not a popup) on the submit click
Or how can I use the validation plugin? I’ve downloaded the .zip file and added(& referenced) the .validate.js file, but the
.validate method doesn’t seem to do anything?
Make sure your form fields have a name attribute, and that you are specifying validation rules either during the plugin declaration or via the built in class feature.
Also you can add a custom validation method right into the plugin and use it like the ones already built in:
Example:
Custom validation method reference: http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
Edit: Just noticed the plugin has a file extension validating method built in:
http://docs.jquery.com/Plugins/Validation/Methods/accept#extension
Edit 2: Here’s how you can validate without using a custom method (using the one I just found built in):