I have a webform that has an ASP file upload object and I want to use jQuery to grab the file they have selected and upload the file via AJAX.
However I am having problems grabbing the file name after it's been selected.
Here is the HTML/ASP Code:
<asp:FileUpload runat="server" ID="NewPic" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="NewPic" runat="server" Display="Dynamic" Text="You need to pick a picture." CssClass="mandatory"></asp:RequiredFieldValidator>
This is what I have tried but doesn't seem to work
uploadText = $('input[type=file]').value;
alert('FileName: ' + uploadText);
Give this a try:
uploadText = $(':file').val();
alert('FileName: ' + uploadText);
I post this even though I'm unsure if input[type=file] behaves differently than input[type=text]. But with input[type=text], you call the val() function and not read a value member variable.
Related
I have a text box control in asp with 3 different validators. Each validator is getting its error message from the server, and each one validates different things.
My problem is that for some values, two or more validators are firing and I'm getting more then one error message.
I would like to make some kind of priority functionality, meaning that if the first validator is firing the other two will not. Is there any way to make the validator behave like that?
I've added some code sample:
<asp:RequiredFieldValidator ID="cvRequired" runat="server" Display="Dynamic"
ControlToValidate="txtBox" />
<asp:RegularExpressionValidator ID="cvFormat" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ValidationExpression="^([A-Za-z])+$" />
<asp:CustomValidator ID="cvCustom" runat="server" Display="Dynamic"
ControlToValidate="txtBox" ClientValidationFunction="validateFunction" />
I want that the format validator and the custom validator will not fire if the required validator is invalid (actually, I just want them to not showing their error message).
As I said, the error messages are from the server, so I can't really join them to one custom validator. Also, the "validateFunction" is in another js file (for re-use).
Few logic options you got to think about,
(txtPhone) having three validators.
1.RangeValidator, 2.CustomValidator 3.Regexvalidator
Say,after validation (check what it returns if validation fails/passes) and act upon that.
if(rangevalidator1 != null)
{
...somecode...
}
I ll suggest you using javascript ..
you can use a single custom validator for all three validation and you put your code in if condition according to your need.
<asp:CustomValidator runat="server" ID="cstmStartDateValidater"
ToolTip="Start date cannot be greater than equal to end date/time or less than current date/time"
ErrorMessage="*" ControlToValidate="txtStartDateTime"
ForeColor="Red" ValidationGroup="vlgMessage" SetFocusOnError="true"
onservervalidate="cstmStartDateValidater_ServerValidate" ></asp:CustomValidator>
in the .cs page
protected void cstmStartDateValidater_ServerValidate(object source, ServerValidateEventArgs args)
{
if (CompareStartDate())
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
you can use following link for more information :
MSDN,
Code Project
hope these will help you .
Make use of ValidatorCalloutExtender control which is available in ajax control toolkit.
Place a separate ValidatorCalloutExtender across each control,you wish to validate it.
I created the upload page using with FileUpload server control. And I used regular expression validator to validate file extension.
<asp:FileUpload ID="AttachmentUpload" CssClass="text" size="58" Width="376px" IE:Width="385px" runat="server"/>
<asp:RequiredFieldValidator SetFocusOnError="true"
ID="AttachmentUploadRequire"
runat="server"
ControlToValidate="AttachmentUpload"
Display="None"
ErrorMessage="Please select a file to attach."/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server"
ErrorMessage="The selected file type is not allowed!"
ControlToValidate="AttachmentUpload"
Display="None"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(\.[mM][pP]3|\.[mM][pP][eE][gG]|\.[sS][wW][fF]|\.[dD][oO][cC]|\.[tT][xX][tT]|\.[jJ][pP][gG]|\.[jJ][pP][eE][gG]|\.[pP][nN][gG]|\.[xX][lL][sS]|\.[pP][dD][fF]|\.[gG][iI][fF]|\.[pP][pP][tT])$"/>
It is Ok for chrome and IE but not Ok for firefox. How can I solve it?
Firefox only supplies the file name information, not its path information. Your regular expression parses for path information, thus it fails.
I believe that other non-IE browsers also only send the file name. The purpose is to protect the user's privacy (i.e.: you could obtain their system username if the file was stored under My Documents in windows).
Consider using a Javascript function and call it on your form button's OnClientClick event. This approach works for all browsers:
function checkFileExtension() {
var filePath = document.getElementById('AttachmentUpload').value;
var validExtension = 'xml';
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
if (ext.toLowerCase() == validExtension)
return true; //xml file is valid
alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
return false; //all other types of files are not valid
}
I have a page with a RadioButtonList which should post back when the selection is changed. But because of RequiredFieldValidator on the page, the postback is not happening.
It is working fine on //localhost/ but not after deployment to production server.
The error on the page is:
'event' is null or not an object
Line: 126
Char: 5
Code: 0
URI: http://web-dev:90/aspnet_client/system_web/2_0_50727/WebUIValidation.js
A few things which I have already tried:
1) aspnet_client folder is in its proper place.
2) I have added Page.Validate() and if(Page.IsValid){} statements with the button on whose click the validation should happen.
3) The ValidatorCommonOnSubmit function in WebUIValidation.js file looks like this:
function ValidatorCommonOnSubmit() {
event.returnValue = !Page_BlockSubmit;
Page_BlockSubmit = false;
return event.returnValue;}
Can somebody help me with this? Any help would be appreciated. Thanks!!
you can group the required field validator related controls so that it wont effect the radio button list.
<asp:RequiredFieldValidator ID="rfv" runat="server" ValidationGroup="button1"
ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button1" ValidationGroup="button1" />
As far as your radio button list is not grouped under "button1" group, it will not have any problem.
Details here and here
I'm trying to use the regular expression validator for a numeric ID field. The field needs to be a required field of any number. Currently, I'm using:
="\d{1,}"
Shouldn't this make it so the user has to at least enter 1 digit?? If I hit the submit button with the field empty, it passes validation and posts back.. But if I enter non-numeric characters, it errors fine. If I wanted zero or more occurrences, I'd use: ="(\d{1,})?"
Why isn't this working? Do I need to use this in combination with a Required Field Validator? That would suck ><
Make sure you set the property ValidateEmptyText to true or else the CustomValidator will not fire for empty text.
EDIT: You can attach a javascript function to the CustomValidator to accomplish this since I don't think a RegularExpressionValidator will fire against an empty control. I have created a basic example to illustrate the solution:
<script type="text/javascript">
function CheckMyText(sender, args) {
var compare = RegExp("\\d{1,}");
args.IsValid = compare.test(args.Value);
return;
}
</script>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" Text="Test" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Error!"
ControlToValidate="txtTest" ValidateEmptyText="true"
ClientValidationFunction="CheckMyText"></asp:CustomValidator>
I have tested it and it seems to work. Leave a comment if you require further assistance.
You still need to use a RequiredFieldValidator.
I'm not sure where the user is entering the IDs, but if the input field is TextBox control why don't you use something like this:
if (tbID.Text.Length != 0)
{
//Logic goes here
}
When user clicks submit, you need to make sure that not only empty strings are captured, below is a regex that looks for any whitespace(tab,space etc) + matches if character is not a digit(0-9)
Dim FoundMatch As Boolean
Try
FoundMatch = Regex.IsMatch(SubjectString, "\Dm/rld$/\s", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
'put your code here
Catch ex As ArgumentException
'syntax error in regular expression
End Try
I believe you'll need to use postback on your page, if you decide to use RequiredFieldValidator you can use above regex expression for that as well
Hth
In case someone is not using a CustomValidator then you can have a RequiredFieldValidator and RegularExpressionValidator for the same control. Found this solution here: http://forums.asp.net/t/1230931.aspx . Normally, this results in the error messages being displaced for the second validator but there is a way to fix that. You just have to set the Display property to dynamic for both the validators. Now the error messages for both the validators are displayed in the same location. Example code:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
ValidationExpression="regexExpression"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
Display="Dynamic"></asp:RequiredFieldValidator>`
How can I get gridview HTML textbox value in .aspx.cs code?? E.g. :
<input id="Frequency" name="customerName" type="text" style="width: 44px" />
If i use the bellow code ,Then i can get the value on selectedIndex event.
string n = String.Format("{0}", Request.QueryString['customerName']);
I want to use bellow syntax.
TextBox_Label1 = (TextBox)e.Row.FindControl("Frequency");
i don't want to user the runat="server" on HTML control .
From Gridview i need to call a popup,Popup return a value ,I use the bellow code on javascript to do that
window.opener.document.getElementById("customerName").value = val;
window.close();
In my gridview .if i put the runat="server" then return value not set ,So i need to remove the runat="server".It also not work if i put the Asp:TextBox on Grid.Help me to Return popup value on gridview Asp:TextBox
Thanks!
Try a databinding expression:
<input id="Frequency" name="customerName" type="text" style="width: 44px"><%# String.Format("{0}", Request.QueryString["customerName"])%></input>
If you're having problems with this process and the difference is one is runat="server" and the other is not, I would suggest you need to look at your JavaScript to make sure that you have the proper element selection method. The rendered ClientID will be different from a standard html control ID. If you write your code so that the ClientID is injected into the JavaScript, you can keep the runat="server" and achieve your results. Standard html controls are not accessible from the code behind.