Disable Validator but Validator Callout still shows and causes validation - asp.net

I'm trying to validate that a certain increment of a product was entered in the product qty textbox that is in a repeater. The problem is that the increment is different for every product, so I need that as a variable for each call to validate it (which I don't think you can do with a custom validator), and I need it client side with a ValidatorCalloutExtender. The best solution i have come up with is to trigger a RegEx validator that will evaluate false via my own javascript (another validator takes care of making sure its a valid number). The problem is that with the ValidatorCalloutExtender, when I disable the validator it still marks it as invalid (the textbox flashes white then turns yellow again (meaning its invalid), even though I placed JavaScript alerts and I know the validator is getting disabled. Anyone have any ideas as to whats going on here? Here is the code. Thanks!
PS: Everything works fine w/out the validatorCalloutExtender, but I really need the Callout Extender!
The validators:
<asp:RegularExpressionValidator ID="ProductIncrementValidator" runat="server"
ControlToValidate="ProductQtyTxt"
ErrorMessage="Please enter a valid increment"
ValidationExpression="^triggerthisvalidation$"
Enabled="false"
Display="Dynamic"
SetFocusOnError="true"
ValidationGroup="productValidation">
</asp:RegularExpressionValidator>
<ajax:ValidatorCalloutExtender ID="ProductIncrementVE" runat="server"
TargetControlID="ProductIncrementValidator"
HighlightCssClass="validator"
WarningIconImageUrl="~/img/blank.gif">
</ajax:ValidatorCalloutExtender>
When Databinding the product:
Dim productQtyTxt As TextBox
productQtyTxt = CType(e.Item.FindControl("ProductQtyTxt"), TextBox)
Dim incrementValidator As RegularExpressionValidator
incrementValidator = CType(e.Item.FindControl("ProductIncrementValidator"), RegularExpressionValidator)
incrementValidator.ErrorMessage = "Please enter an increment of " & product.OrderIncrement.ToString()
' Add item qty increment check
productQtyTxt.Attributes.Add("onChange", "javascript:checkIncrement('" _
& productQtyTxt.ClientID & "', " _
& product.OrderIncrement & ", '" _
& incrementValidator.ClientID & "')")
The Javascript:
function checkIncrement(textboxID, incrementQty, validatorID) {
var textbox = $get(textboxID);
var incrementValidator = $get(validatorID);
var qtyEntered = textbox.value;
if ((qtyEntered % incrementQty) != 0) {
ValidatorEnable(incrementValidator, true);
alert("not valid");
return;
}
else {
ValidatorEnable(incrementValidator, false);
alert("valid");
return;
}
}

1.Set CSS class for ValidatorCalloutExtender:
<style id = "style1" type="text/css">
.CustomValidator
{
position: relative;
margin-left: -80px;
margin-top: 8px;
display: inherit;
}
</style>
<ajax:ValidatorCalloutExtender ID="ProductIncrementVE" runat="server"
TargetControlID="ProductIncrementValidator"
HighlightCssClass="validator"
WarningIconImageUrl="~/img/blank.gif"
CssClass="CustomValidator">
</ajax:ValidatorCalloutExtender>
2 . Use JavaScript to alter this CSS class when needed. Set display = none:
function alterDisplay(type) {
var styleSheet, cssRule;
if (document.styleSheets) {
styleSheet = document.styleSheets[index1];
if (styleSheet) {
if (styleSheet.cssRules)
cssRule = styleSheet.cssRules[index2]; // Firefox
else if (styleSheet.rules)
cssRule = styleSheet.rules[index2]; // IE
if (cssRule) {
cssRule.style.display = type;
}
}
}
}
Note: the index1 and index2 may be difference from pages, it's up to your declaration. You can use IE debugger to find our the correctly indexs.

I had the same problem, i solved with something like this
if ((qtyEntered % incrementQty) != 0) {
ValidatorEnable(incrementValidator, true);
$("#" + validatorID + "_ValidatorCalloutExtender_popupTable").show();
alert("not valid");
return;
}
else {
ValidatorEnable(incrementValidator, false);
$("#" + validatorID + "_ValidatorCalloutExtender_popupTable").hide();
alert("valid");
return;
}
Hope this helps someone.

Related

Empty text box using requiredvalidator

I am currently involved in developing a system using asp.net(VB). I have applied required validator so that to obtain correct inputs from user. But now I am having some issues. I also must allow the user to leave the text boxes empty too. Then can submit the page. so consider the form can validate true if thetext box are left empty or with values.
how to solve this issue frends? Kindly help me. Thank You very much
When you use a required Validator, the text will be required. Hence the name...
If you want more complex validation you need to use a CustomValidator
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Text not long enough" ValidationGroup="myGroup" ClientValidationFunction="myCustomValidation"></asp:CustomValidator>
<script type="text/javascript">
function myCustomValidation(oSrc, args) {
var textboxValue = args.Value;
if (textboxValue == "") {
args.IsValid = true;
} else {
if (textboxValue.length > 4) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
}
</script>

How do I highlight a textbox border red when it is required?

What property do I use on the required field validator control to make the textbox red if there is a validation error?
Here is my code:
<asp:Label ID="lblFirstName" runat="server" AssociatedControlID="txtFirstName" Text="First Name:" CssClass="reg-labels" />
<br />
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60" CssClass="standard_width"/>
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />
ASP.Net web forms internally uses a Javascript frameworka located at aspnet_client\{0}\{1} folder to handle the validation, etc. They are basically determined from the property ClientScriptsLocation
Try overriding the default framework function by keeping it in your page includes additional line to set the control_to_validate color
document.getElmentById(val.controltovalidate).style.border='1px solid red';
<asp:TextBox ID="txtFirstName" runat="server" CausesValidation="true" MaxLength="60"
CssClass="standard_width" />
<asp:RequiredFieldValidator ControlToValidate="txtFirstName" runat="server" ID="valFirstName" ValidationGroup="grpRegistration" ErrorMessage="First Name is required." Text="*" />
<asp:Button Text="Super" ID="btnSubmit" CausesValidation="true" runat="server" />
JS
<script type="text/javascript">
function ValidatorUpdateDisplay(val) {
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
if (val.isvalid) {
document.getElementById(val.controltovalidate).style.border = '1px solid #333';
}
else {
document.getElementById(val.controltovalidate).style.border = '1px solid red';
}
}
</script>
Without overloading anything, give your <asp:*Validator tags a CssClass="garbage" attribute.
In your style sheet, create
.garbage {
display: none;
}
.garbage[style*=visible] + input,
.garbage[style*=visible] + select,
.garbage[style*=visible] + textarea {
background-color: #ffcccc;
border: 1px solid #ff0000;
}
and any form control immediately preceded by a validator will be highlighted on invalid data.
EDIT:
I've seen a few methods for forcing a redraw in Chrome, including a pure css solution: transform: translateZ(0);
Murali's answer works great, but I rolled a jQuery version for myself if anyone's interested.
Based on the official documentation (https://msdn.microsoft.com/en-us/library/yb52a4x0.aspx), I was able to get each validator and check to see if it isvalid, and if not, use the errormessage property to populate my own notification system (setStatusMessage() is a function I wrote, feel free to use any other type of status message prompt, like alert() or roll your own).
/*
* Validation Catcher - Sean D Kendle - 9/24/2015
* Catch validation events and add to status messages system
*/
$(document).on("submit", function () {
$.each(Page_Validators, function (i, v) {
var strControlToValidateID = v.controltovalidate;
var $controlToValidate = $("#" + strControlToValidateID);
var arrInvalidControls = new Array(); //collection of all invalid field ids for later
if (!v.isvalid) {
$controlToValidate.addClass("error"); //custom error class, optional
$controlToValidate.css("border-color", "#D00"); //manually set border-color per OP's question
$(".error").eq(0).focus(); /*set focus to top-most invalid field on error, or you can use the v.focusOnError property to check if validator has this set (string "t" if true), but I don't want to have to set this every time*/
arrInvalidControls.push(strControlToValidateID); //collect all invalid field ids for later
$(v).addClass("redtext"); //custom class - allows me to make all errors red without having to add a ForeColor property to every validator
setStatusMessage(v.errormessage, "red", -1); // setStatusMessage is a function I wrote, replace with another alert system if desired, or delete this line
} else {
/*the following prevents control being seen as valid if there are two or more validators for the control - example: required field validator, then custom or regex validator (first would be invalid, second would be valid for empty field)*/
if (!$.inArray(strControlToValidateID, arrInvalidControls)) {
$controlToValidate.removeClass("error");
$controlToValidate.css("border-color", "");
} else {
//console.log(strControlToValidateID + " is already invalid.");
}
}
});
});
I hope this helps someone!
Well, to your disappointment there isn't a direct way (cf https://stackoverflow.com/a/5249021/145682)
However, you can make use of a CustomValidator. Here is one way to define it:
<asp:TextBox ID="txtbx" runat="server"></asp:TextBox>
<asp:CustomValidator ID="customValidator"
runat="server" ValidationGroup="submit" ControlToValidate="txtbx"
ClientValidationFunction="foo" ErrorMessage="*"></asp:CustomValidator>
Make note of the ClientValidationFunction. It has to be written as follows:
function foo(sender, e) {
var value = e.Value;
console.log('Value: ', e.Value);
var ctrlid = sender.controltovalidate;
var targetControl = document.getElementById(ctrlid);
if (vowels.indexOf(value[0].toLowerCase()) == -1) {
console.log('true-executed');
e.isValid = false;
targetControl.style.borderColor = 'red';
}
else {
console.log('else-executed');
e.isValid = true;
targetControl.style.borderColor = '';
}
}
The controltovalidate property of sender will give you the id of the control you are looking for; in other words, your ControlToValidate. And, Value property of e should give you the target control's value.
The other option, is you can write your own server control to do the job: http://msdn.microsoft.com/en-us/library/aa719624(v=vs.71).aspx
Murali's answer worked for me as data changes, but on postback all the fields rendered as though there were no validation errors. I found that ASP.NET lazy-loads ValidatorUpdateDisplay, so the client-side override doesn't take effect until after it's already passed its onload validation. I'm guessing there's either a version or an implementation difference that blocked me here, but other solutions (including a few with CSS) weren't working either.
Eventually, I came upon a solution that combines Murali's answer with Dillie-O's solution from here: Change Text Box Color using Required Field Validator. No Extender Controls Please
<div class="pad-left">
<asp:CompareValidator ID="comvIncTaxable" runat="server" ControlToValidate="tbIncTaxable" Display="Dynamic" Operator="DataTypeCheck" Type="Currency" CssClass="red-border"
ErrorMessage="Please enter a currency value.">
<span></span>
</asp:CompareValidator>
<asp:TextBox runat="server" ID="tbIncTaxable"></asp:TextBox>
</div>
<script type="text/javascript">
$(function () {
setValidatedBordersOnLoad();
});
function ValidatorUpdateDisplay(val) {
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
if (val.className == 'red-border' && val.controltovalidate) {
if (val.isvalid) {
document.getElementById(val.controltovalidate).style.border = '1px solid #ccc';
}
else {
document.getElementById(val.controltovalidate).style.border = '1px solid red';
}
}
return;
}
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
function setValidatedBordersOnLoad()
{
for (var i = 0; i < Page_Validators.length; i++)
{
var val = Page_Validators[i];
if (val.className == 'red-border' && val.controltovalidate) {
var ctrl = document.getElementById(val.controltovalidate);
if (ctrl != null && ctrl.style != null) {
if (!val.isvalid)
ctrl.style.border = '1px solid red';
else
ctrl.style.border = '1px solid #ccc';
}
}
}
}
</script>
The nice thing about this solution is it lets you cherry-pick which validators get this special handling simply by adding CssClass='red-border' to the validator. In my case, I only wanted this behavior on fields within a specific grid where cell positioning shouldn't change, but still wanted to use out-of-box functionality elsewhere on the form.

How to set maxlength for multiline TextBox?

When using a MultiLine TextBox (which generates a TextArea) setting the MaxLength property has no effect. What is the best workaround? I'd like to get basic, intended functionality with minimum of ugly javascript etc. Just prevent user from entering more than max number of characters.
If you don't care about older browsers (see supported browsers here),
you can set MaxLength normally like this
<asp:TextBox ID="txt1" runat="server" TextMode="MultiLine" MaxLength="100" />
and force it to be printed out to the HTML
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txt1.Attributes.Add("maxlength", txt1.MaxLength.ToString());
}
If you want to let the user know if he exceeded the amount of characters as he writes, you could use a javascript function attached to keypress event. This function would test the length of the input and cancel the character rendering if the maxlenght was reached.
Another option is to use RegularExpressionValidator control to validate the input on submit.
In my opinion, the first option is much more better.
I'm not adding any code since google is full of examples for all tastes, this is a very common task.
Here you have a sample search that might help.
Hey pukipuki you can do as follows:
<asp:TextBox ID="txtValue" runat="server"TextMode="MultiLine" Rows="10"Columns="50"></asp:TextBox>
$(document).ready(function(){
var MaxLength = 250;
$('#txtValue').keypress(function(e)
{
if ($(this).val().length >= MaxLength)
{
e.preventDefault();
}
});});
You can see more in this following link:
http://jquerybyexample.blogspot.in/2010/10/set-max-length-for-aspnet-multiline.html
Here's a cross browser solution :
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtPurpose" Columns="50" Rows="2" onkeypress="return isokmaxlength(event,this,255);" ClientIDMode="static"></asp:TextBox>
Javascript :
function isokmaxlength(e,val,maxlengt) {
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
if (!(charCode == 44 || charCode == 46 || charCode == 0 || charCode == 8 || (val.value.length < maxlengt))) {
return false;
}
}
You have to think about the Copy and Paste. This is a little bit tricky, I simply disable it with Jquery. But you can create your own function to do more complex verification. But in my case, copy and paste is not allowed.
Jquery to disable copy and paste :
jQuery(function ($) {
$("#txtPurpose").bind({
paste: function (e) {
e.preventDefault();
}
});
});
If you are using a model object bind to that textbox you can use DataAnnotations attributes to set the maxlength of that property. I'm based on MVC about that but it should work for ASP.NET too!
This way you don't mess with any Javascript or setting anything in the markup.
Try this..
Dim script As String = ""
script = script + " <script type='text/javascript'> function CheckLength(obj) {"
script = script + " var object = document.getElementById(obj);"
script = script + " if (object.value.length > 5) {"
script = script + " object.focus();"
script = script + " object.value = object.value.substring(0, 5); "
script = script + " object.scrollTop = object.scrollHeight; "
script = script + " return false;"
script = script + " }"
script = script + " return true;"
script = script + " }</script>"
Dim b As New TextBox()
b.ID = "btnSomeButton"
b.TextMode = TextBoxMode.MultiLine
Mypanel.Controls.Add(b)
b.Attributes.Add("onkeyup", "return CheckLength('" & b.ClientID & "');")
Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", script, False)
To force asp.net to send the maxlength attribute for all multiline textboxes on a page or a whole site,
building on Aximili's answer above:
Create a function to get all the controls on the page:
I use the control extension method from David Findley
https://weblogs.asp.net/dfindley/linq-the-uber-findcontrol
and referenced in this SO post
Loop through all controls on asp.net webpage
namespace xyz.Extensions
{
public static class PageExtensions
{
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
}
}
In the page or master page
Make sure to reference the namespace for the extension method in step 1.
Put the following code in the Page_Load function:
if (!IsPostBack){
//force textareas to display maxlength attribute
Page.Controls.All().OfType<TextBox>().ToList()
.Where(x => x.TextMode == TextBoxMode.MultiLine && x.MaxLength > 0)
.ToList().ForEach(t => t.Attributes.Add("maxlength", t.MaxLength.ToString()));
}

Asp.Net Check file size before upload

I want to check the selected file size BEFORE uploading a file with the asp fileupload component.
I can not use activex because the solution have to works on each browser (firefox, Chrome, etc..)
How can I do that ?
Thanks for your answers..
ASPX
<asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" />
<asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" />
<asp:Label ID="lbl_uploadMessage" runat="server" Text="" />
jQuery
function setUploadButtonState() {
var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024
var fileUpload = $('#fileUpload');
if (fileUpload.val() == '') {
return false;
}
else {
if (fileUpload[0].files[0].size < maxFileSize) {
$('#button_fileUpload').prop('disabled', false);
return true;
}else{
$('#lbl_uploadMessage').text('File too big !')
return false;
}
}
}
I am in the same boat and found a working solution IF your expected upload file is an image. In short I updated the ASP.NET FileUpload control to call a javascript function to display a thumbnail of the selected file, and then before calling the form submit then checking the image to check the file size. Enough talk, let's get to the code.
Javascript, include in page header
function ShowThumbnail() {
var aspFileUpload = document.getElementById("FileUpload1");
var errorLabel = document.getElementById("ErrorLabel");
var img = document.getElementById("imgUploadThumbnail");
var fileName = aspFileUpload.value;
var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
if (ext == "jpeg" || ext == "jpg" || ext == "png") {
img.src = fileName;
}
else {
img.src = "../Images/blank.gif";
errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
}
img.focus();
}
function CheckImageSize() {
var aspFileUpload = document.getElementById("FileUpload1");
var errorLabel = document.getElementById("ErrorLabel");
var img = document.getElementById("imgUploadThumbnail");
var fileName = aspFileUpload.value;
var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
if (!(ext == "jpeg" || ext == "jpg" || ext == "png")) {
errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
return false;
}
if (img.fileSize == -1) {
errorLabel.innerHTML = "Couldn't load image file size. Please try to save again.";
return false;
}
else if (img.fileSize <= 3145728) {
errorLabel.innerHTML = "";
return true;
}
else {
var fileSize = (img.fileSize / 1048576);
errorLabel.innerHTML = "File is too large, must select file under 3 Mb. File Size: " + fileSize.toFixed(1) + " Mb";
return false;
}
}
The CheckImageSize is looking for a file less than 3 Mb (3145728), update this to whatever value you need.
ASP HTML Code
<!-- Insert into existing ASP page -->
<div style="float: right; width: 100px; height: 100px;"><img id="imgUploadThumbnail" alt="Uploaded Thumbnail" src="../Images/blank.gif" style="width: 100px; height: 100px" /></div>
<asp:FileUpload ID="FileUpload1" runat="server" onchange="Javascript: ShowThumbnail();"/>
<br />
<asp:Label ID="ErrorLabel" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click" Width="70px" OnClientClick="Javascript: return CheckImageSize()" />
Note the browser does take a second to update the page with the thumbnail and if the user is able to click the Save before the image gets loaded it will get a -1 for the file size and display the error to click save again. If you don't want to display the image you can make the image control invisible and this should work. You will also need to get a copy of blank.gif so the page doesn't load with a broken image link.
Hope you find this quick and easy to drop in and helpful. I'm not sure if there is a similar HTML control that could be used for just general files.
Here I come to save the day! sorry i am 3 years late but, let me reassure everyone that this is quite possible and not to hard to implement! You simply need to output the filesize of the file being uploaded to a control that can be validated. You can do this with javascript, which will not require an ugly postback, where as if you were to use
FileBytes.Length
you will encounter a postback after the end user has selected an image. (I.E. using the onchange="file1_onchange(this);" to accomplish this.). Whichever way you choose to output the filesize is up to you the developer.
Once you have the filzesize then simply output it to a ASP control that can be validated. (I.E. a textbox) then you can use a regular expression for a range to validate for your filesize.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^([1-9][0-9]{0,5}|[12][0-9]{6}|3(0[0-9]{5}|1([0-3][0-9]{4}|4([0-4][0-9]{3}|5([0-6][0-9]{2}|7([01][0-9]|2[0-8]))))))$" ErrorMessage="File is too large, must select file under 3 Mb." ControlToValidate="Textbox1" runat="server"></asp:RegularExpressionValidator>
Boom! it's that easy. Just make sure to use the Visibility=Hidden on your ASP control to be validated and not Display=None because Display=none will appear on the page at all (although you can still interact with it through the dom). And Visibility=Hidden is not visible, but space is allocated for it on the page.
check out: http://utilitymill.com/utility/Regex_For_Range for all your regex range needs!
I think it is possible using javascript look here
I think you cannot do that.
Your question is similar to this one : Obtain filesize without using FileSystemObject in JavaScript
The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server.
So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
You can do that by using javascript.
Example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileSize() {
var input, file;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
}
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
</form>
</body>
</html>
To validate multiple files with jQuery + asp:CustomValidator a size up to 10MB
jQuery:
function upload(sender, args) {
args.IsValid = true;
var maxFileSize = 10 * 1024 * 1024; // 10MB
var CurrentSize = 0;
var fileUpload = $("[id$='fuUpload']");
for (var i = 0; i < fileUpload[0].files.length; i++) {
CurrentSize = CurrentSize + fileUpload[0].files[i].size;
}
args.IsValid = CurrentSize < maxFileSize;
}
ASP:
<asp:FileUpload runat="server" AllowMultiple="true" ID="fuUpload" />
<asp:LinkButton runat="server" Text="Upload" OnClick="btnUpload_Click"
CausesValidation="true" ValidationGroup="vgFileUpload"></asp:LinkButton>
<asp:CustomValidator ControlToValidate="fuUpload" ClientValidationFunction="upload"
runat="server" ErrorMessage="Error!" ValidationGroup="vgFileUpload"/>
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: http://blueimp.github.io/jQuery-File-Upload/
It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx
$(document).ready(function () {
"use strict";
//This is the CssClass of the FileUpload control
var fileUploadClass = ".attachmentFileUploader",
//this is the CssClass of my save button
saveButtonClass = ".saveButton",
//this is the CssClass of the label which displays a error if any
isTheFileSizeTooBigClass = ".isTheFileSizeTooBig";
/**
* #desc This function checks to see what size of file the user is attempting to upload.
* It will also display a error and disable/enable the "submit/save" button.
*/
function checkFileSizeBeforeServerAttemptToUpload() {
//my max file size, more exact than 10240000
var maxFileSize = 10485760 // 10MB -> 10000 * 1024
//If the file upload does not exist, lets get outta this function
if ($(fileUploadClass).val() === "") {
//break out of this function because no FileUpload control was found
return false;
}
else {
if ($(fileUploadClass)[0].files[0].size <= maxFileSize) {
//no errors, hide the label that holds the error
$(isTheFileSizeTooBigClass).hide();
//remove the disabled attribute and show the save button
$(saveButtonClass).removeAttr("disabled");
$(saveButtonClass).attr("enabled", "enabled");
} else {
//this sets the error message to a label on the page
$(isTheFileSizeTooBigClass).text("Please upload a file less than 10MB.");
//file size error, show the label that holds the error
$(isTheFileSizeTooBigClass).show();
//remove the enabled attribute and disable the save button
$(saveButtonClass).removeAttr("enabled");
$(saveButtonClass).attr("disabled", "disabled");
}
}
}
//When the file upload control changes, lets execute the function that checks the file size.
$(fileUploadClass).change(function () {
//call our function
checkFileSizeBeforeServerAttemptToUpload();
});
});
dont forget you probably need to change the web.config to limit uploads of certain sizes as well since the default is 4MB
https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx
<httpRuntime targetFramework="4.5" maxRequestLength="11264" />
Why not to use RegularExpressionValidator for file type validation.
Regular expression for File type validation is:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"

How to go about validating AJAX cascading drop down lists

I am using the AJAX Cascading drop down list but want to add event validation e.g. the compare validators.
As the cascading drop down list requires the page event validation to be disabled what is the best way to do the validation?
Thanks
Andy
Validation Attempt:
I have tried to use a custom validator which calls a Javascript function but it doesnt seem to be picking up the control. I get the following error Microsoft JScript runtime error: Object required
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("ddlCategory");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if (iValue == "Select Category")
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
}
}
The mark-up for the custom validator is
<asp:CustomValidator ID="valcustCategory" runat="server" CssClass="error" Display="Dynamic" ValidationGroup="DirectHire" ClientValidationFunction="ValidateCostCentCat"
ErrorMessage="Please select a Cost Centre Category from the drop down list provided.">!</asp:CustomValidator>
Read This: http://www.w3schools.com/PHP/php_ajax_database.asp
The example demostrate how to select a
value from a dropdown box sent it via
AJAX and get back the responce!
in the middle you can do all the
Validation that you want!
UPDATED with code just for fun! ;-)
Assuming your select is
<asp:DropDownList ID="CategoryDropDownList" runat="server">
Then you function look like this:
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("CategoryDropDownList");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if ( iValue == "Select Category" ) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
}
This must work as expected!
hope this help!

Resources