How to use RegularExpressionValidator to validate Image extension in Asp.Net - c#

<asp:FileUpload ID="FUpImg1" runat="server" CssClass="control-label" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="FUpImg1" ValidationExpression="(.*?)\.(jpg|png|JPG|PNG)$"
CssClass="text-danger" ErrorMessage="Please Upload .jpg, .png only" Display="Dynamic"></asp:RegularExpressionValidator>
its not working its directly going on server side not validate my image extension. what is wrong with above code?
Thanks in advance!

RegularExpressionValidator only validate when i upload anything in the FileUploader!
that why its not validate anything when its null and going on server side in my question.
i use customvalidator with js function because i have 5 different FileUploader and i have to pass same function.
function validateImageExtension(source, args) {
var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.png|.jpeg)$/;
if (args.Value == "" || args.valueOf == null) {
args.IsValid = false;
source.innerText = "Image is Required*";
}
else {
//Checks with the control value.
if (reg.test(args.Value)) {
args.IsValid = true;
source.innerText = "";
}
else {
//If the condition not satisfied shows error message.
args.IsValid = false;
source.innerText = "Only .jpg, .png, .jpeg files are allowed!";
}
}
}
idk how it work btw. i just copy paste it from 5 different blogs.

Related

How to use multiple Regular expressions in ASP.NET Web Forms Regular Expression validator

I need to validate some control's input against multiple regular expressions how can i do this with one Regular Expression validator control.
There's no way. You need a regular expression validator for each regex you want to test.
Try to build a regular expression using the OR operator. Check this links for more information about it:
http://forums.asp.net/t/1213089.aspx?Multiple+Format+in+Regular+Expression+Validator
https://msdn.microsoft.com/en-us/library/aa976858(v=vs.71).aspx
If it's not possible to adapt and build a regular expression acording to your needs, you can use a custom validator and make all the validatations for each regular expression that you could need. Check this link for more information about Custom Validator.
I think the only solution to your problem is to use a custom validator.check the below code.this is just to give you an idea about how to use custom validator.
<asp:TextBox runat="server" ID="UserName" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="UserName" ></asp:CustomValidator>
protected void ValidateUser(object source, ServerValidateEventArgs args)
{
Regex regx = new Regex("^[a-zA-Z0-9]{6,}$");
Regex regx2 = new Regex("^[a-zA-Z0-9]{6,}$");
if (regx.IsMatch(UserName.Text) == false)
{
CustomValidator1.ErrorMessage = "error message";
args.IsValid = false;
}
else if(regx2.IsMatch(UserName.Text) == false)
{
CustomValidator1.ErrorMessage = "second error message";
args.IsValid = false;
}
else
{args.IsValid = true;}
}

How can I cancel ajaxToolkit:AjaxFileUpload inside OnClientUploadStart?

I'm trying to do some validation of some other fields on the page after the user clicks the upload button of the ajaxfileupload control. OnClientUploadStart is defined to fire before the upload starts. and it works. but I want to cancel the upload if the validation fails.
I tried doing "return false;" but that didn't work.
How can I cancel the upload?
if the validation fails then I want to cancel
function uploadStart(sender, args) {
var FileDescription = document.getElementById("FileDescription").value;
alert( FileDescription);
return false;
}
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1"
ThrobberID="myThrobber" OnUploadComplete="AjaxFileUpload1_UploadComplete"
ContextKeys="" OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete" OnClientUploadStart="uploadStart"
AllowedFileTypes="jpg,jpeg,doc,xls"
MaximumNumberOfFiles="1"
runat="server"/>
To start uploading manually you can use this script:
function startUpload(){
$get("<%= AjaxFileUpload1.ClientID %>_UploadOrCancelButton").click();
}
Cancel download large files (works only for browsers that support HTML5).
function uploadStartedAjax(sender, args) {
var maxFileSize = $('#MaxRequestLength').val();
for (var i = 0; i < sender._filesInQueue.length; i++) {
var file_size = sender._filesInQueue[i]._fileSize;
if (file_size > maxFileSize) {
sender._filesInQueue[i].setStatus("cancelled", Sys.Extended.UI.Resources.AjaxFileUpload_Canceled+' - too large(> ' + maxFileSize + ' byte)!');
sender._filesInQueue[i]._isUploaded = true;
} //End if
} //End for
return true;
}
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" MaximumNumberOfFiles="200" Width ="750px"
OnClientUploadStart="uploadStartedAjax" />

CustomValidator not calling javascript

I am trying customvalidator control of asp.net but the problem is that it is not calling the javascript function. However it is calling the server side version of the validation method..
<asp:CustomValidator EnableClientScript="true"
ID="RegularExpressionValidatorFixedNames" runat="server" ControlToValidate="TextBoxChapterName"
Text="Name not allowed" Font-Size="XX-Small"
ValidationGroup="Name"
ClientValidationFunction="LQA_Validate"
onservervalidate="RegularExpressionValidatorFixedNames_ServerValidate"> </asp:CustomValidator>
the javascript function
function LQA_Validate(sender, args) {
var re = /(?! My Ls|My As|My Qs).*/ig;
args.IsValid = re.test(args);
}
the server side method
protected void RegularExpressionValidatorFixedNames_ServerValidate(object source, ServerValidateEventArgs args)
{
Regex regex = new Regex(#"^(?!My Ls|My Qs|My As).*", RegexOptions.IgnoreCase);
args.IsValid = regex.IsMatch(args.Value);
}
what can be the problem is this problem because of the regex or I am doing some technical mistake?
The problem is this:
function LQA_Validate(sender, args) {
var re = /(?! My Ls|My As|My Qs).*/ig;
args.IsValid = re.test(args);
}
In re.test(args) you should use re.test(args.Value);
So the code must be:
function LQA_Validate(sender, args) {
var re = /(?! My Ls|My As|My Qs).*/ig;
args.IsValid = re.test(args.Value);
}

c#.net postback of form not keeping 1 value

Having a strange problem regarding the postback of a form I've created. The answer will probably be really simple, but I can't seem to see it.
I have a form that a user can fill in if the page a video is on, isn't working. It pre-populates fields based on the current video selected, and allows the user to fill in other fields, and send the email to me for support.
The problem
The fields are pre-populated correctly, but one of the fields 'Page', although pre-populated correctly, doesn't pass the value to the button submit method.
the clientside code
(includes some mootools javascript, this works)
<asp:Panel ID="pnlVideoProblem" runat="server" Visible="false">
<h2>Report a video/learning tool issue</h2>
<div class="keyline"></div>
<fieldset class="emailform">
<ul>
<li><label>Name <span class="error">*</span></label><asp:TextBox ID="txtVideoName" runat="server" MaxLength="60"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator33" runat="server" CssClass="error" ControlToValidate="txtVideoName" ErrorMessage="Required"></asp:RequiredFieldValidator></li>
<li><label>Email <span class="error">*</span></label><asp:TextBox ID="txtVideoEmail" runat="server" MaxLength="100"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator35" runat="server" CssClass="error" ControlToValidate="txtVideoEmail" ErrorMessage="Required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server" ControlToValidate="txtVideoEmail" Text="Invalid email" ErrorMessage="Email address is not in the correct format" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator></li>
<li><label>OTHER FIELD</label><asp:TextBox ID="txtOtherField" runat="server" MaxLength="10"></asp:TextBox></li>
<li><label>Video ID</label><asp:TextBox ID="txtVideoID" runat="server" ReadOnly="true"></asp:TextBox></li>
<li><label>Browser/Version </label><asp:TextBox ID="txtVideoBrowser" runat="server" MaxLength="100"></asp:TextBox></li>
<li><label>Flash Version </label><asp:TextBox ID="txtFlashVersion" runat="server"></asp:TextBox></li>
<li><label>Page </label><asp:TextBox ID="txtVideoPage" runat="server"></asp:TextBox></li>
<li><label>Visible error messages </label><asp:TextBox ID="txtVisError" runat="server" TextMode="MultiLine" Rows="6" MaxLength="4000"></asp:TextBox></li>
</ul>
<asp:Button ID="btnSubmitVideoIssue" runat="server" CssClass="subbutton" Text="Submit report" OnClick="btnSubmitVideoIssue_Click" />
</fieldset>
<script type="text/javascript">
window.addEvent('domready', function () {
document.id('<%= txtVideoBrowser.ClientID %>').set('value', Browser.Platform.name + ", " + Browser.name + " " + Browser.version);
document.id('<%= txtFlashVersion.ClientID %>').set('value', Browser.Plugins.Flash.version + "." + Browser.Plugins.Flash.build);
});
</script>
</asp:Panel>
the page-behind code for the button
(there is no reseting of the values on postback)
protected void btnSubmitVideoIssue_Click(object sender, EventArgs e)
{
if (CheckEmptyCaptcha() == false)
{
//this field is hidden in css and empty. if it has been filled in, then an automated way of entering has been used.
//ignore and send no email.
}
else
{
StringBuilder sbMessage = new StringBuilder();
emailForm = new MailMessage();
sbMessage.Append("Name : " + txtVideoName.Text.Trim() + "<br>");
sbMessage.Append("Email : " + txtVideoEmail.Text.Trim() + "<br>");
sbMessage.Append("Other Field : " + txtOtherField.Text.Trim() + "<br>");
sbMessage.Append("Video ID : " + txtVideoID.Text.Trim() + "<br>");
sbMessage.Append("Browser : " + txtVideoBrowser.Text.Trim() + "<br>");
sbMessage.Append("Flash Version : " + txtFlashVersion.Text.Trim() + "<br>");
sbMessage.Append("Visible error messages : " + txtVisError.Text.Trim() + "<br>");
sbMessage.Append("Url referrer : " + txtVideoPage.Text.Trim()+"<br>");
sbMessage.Append("Browser : " + Request.UserAgent + "<br>");
if (txtVideoBrowser.Text.Contains("ie 6"))
{
sbMessage.Append("<strong>Browser note</strong> : The PC that made this request looks like it was using Internet Explorer 6, although videos work in IE6, the browser isn't stable software, and therefore Javascript errors may occur preventing the viewing of the page/video/learning tool how it was intended. Recommend that the user upgrades their browsers to the latest version of IE.<br>");
}
Double flashver = 0.0;
if(Double.TryParse(txtFlashVersion.Text, out flashver))
{
if(flashver < 9.0)
{
sbMessage.Append("<strong>Flash version note</strong> : The PC that made this request is currently using flash version "+flashver+". Flash version 9 or greater is required to view videos. Recommend user upgrades their flash version by visiting http://get.adobe.com/flashplayer<br>");
}
}
else
{
sbMessage.Append("<strong>Flash version note</strong> : It doesn't look like flash is installed on the PC that made this request. Flash is required to view videos . Recommend user installs flash by visiting http://get.adobe.com/flashplayer<br>");
}
emailForm.To.Add(new MailAddress("admin#test.com"));
emailForm.From = new MailAddress(txtVideoEmail.Text.Trim(), txtVideoName.Text.Trim());
emailForm.Subject = "[ERROR] - [VIDEO ISSUE] from " + txtVideoName.Text.Trim();
emailForm.Body = sbMessage.ToString();
emailForm.IsBodyHtml = true;
bool sendSuccess = false;
try
{
SmtpClient smtp = new SmtpClient();
smtp.Send(emailForm);
sendSuccess = true;
}
catch
{
pnlVideoProblem.Visible = false;
pnlFailure.Visible = true;
ltlFailure.Text = "There was a problem sending your feedback, please go back and try again.";
}
finally
{
if (sendSuccess)
{
pnlVideoProblem.Visible = false;
pnlSuccess.Visible = true;
ltlSuccess.Text = "Thank you, your feedback has been sent. Click close to return to the website.";
}
else
{
pnlVideoProblem.Visible = false;
pnlFailure.Visible = true;
ltlFailure.Text = "There was a problem sending your feedback, please go back and try again.";
}
}
}
}
the form values
Name : User
Email : User#test.com
Other Field : aab123
Video Learning ID : 5546
Browser version : win, firefox 9
Flash version : 11.102
Page : https://www.awebsite.com/library/video/5546
Visible error messages : ewrwerwe
the resulting email
Name : User
Email : user#test.com
Other Field : aab123
Video ID : 5546
Browser : win, firefox 9
Flash Version : 11.102
Url referrer :
Visible error messages : ewrwerwe
Video ID and Page/Url Referrer are populated on (!IsPostBack)
(!IsPostBack)
pnlVideoProblem.Visible = true;
if (!String.IsNullOrEmpty(Request.QueryString["vid"]))
{
txtVideoID.Text = Request.QueryString["vid"];
}
if (!String.IsNullOrEmpty(Request.QueryString["other"]))
{
txtOtherField.Text = Request.QueryString["other"];
txtOtherField.ReadOnly = true;
}
txtVideoPage.Text = HttpUtility.UrlDecode(Request.QueryString["ref"]);
txtVideoPage.ReadOnly = true;
any ideas? I have a brick wall i can hit my head against based on how simple the answer is.
If TextBox's ReadOnly property is "true", postback data won't be
loaded e.g it essentially means TextBox being readonly from
server-side standpoint (client-side changes will be ignored).
If you want TB to be readonly in the "old manner" use:
TextBox1.Attributes.Add("readonly","readonly")
as that won't affect server-side functionality.
From: http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx
See also: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.readonly.aspx
Solved :)
After a tiny ray of sunshine i remembered I had this
RewriteRule ^/pop/(.*[^/])/report-issue/([a-fA-F0-9]{32})-([0-9]+)$ /pop.aspx?tp=$1&pg=report-issue&vid=$2&other=$3&ref=%{HTTP_REFERER} [L]
as a rewrite rule, which then led me to take a closer look at whether the form fieldswere actually was wrapped in a postback. Lo-and-behold, they werent.
I've wrapped a !postback around the querystring variable reading section and it works!
brick wall needs to be very thick.
thanks to those that tried to help!

Asp.Net custom validation control not showing error messages

The following code is used to validate when form submit button is hit, but I am not getting the wanted result back.
It should display the error messages but they are not being displayed what am I doing wrong?
The custom validator validates passwords, it should change the error message based on the which errors occur:
Password is blank
Password is invalid
Passwords do not match
Only one error should show at a time so I wrote this custom validtor in .ascx.cs:
protected void cvPasswordValidation_ServerValidate(object source, ServerValidateEventArgs args)
{
bool IsPasswordBlank = false;
bool IsPasswordValid = false;
cvPasswordValidation.IsValid = false;
// If password is blank then IsValid is false, show blank password errors.
if (String.IsNullOrEmpty(args.Value))
{
//args.IsValid = false;
IsPasswordBlank = true;
//Show blank password error depending on which box is empty.
if (String.IsNullOrEmpty(txtPassword.Text))
{
cvPasswordValidation.ErrorMessage = "You must enter password";
}
else
{
cvPasswordValidation.ErrorMessage = "You must confirm password";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If password is not valid format then IsValid is false, show invalid format errors.
if (!Regex.IsMatch(args.Value, RegexHelper.ValidPassword))
{
IsPasswordValid = true;
//Show invalid format errors, if password is not blank
if (IsPasswordBlank == false)
{
cvPasswordValidation.ErrorMessage = "<b>Current password</b> not in correct format. Your password must contain 6 - 12 characters with a combination of numbers and letters.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If passwords do not match then IsValid is false, show do not match errors.
bool areEqual = String.Equals(txtPassword.Text, txtConfirmPassword.Text, StringComparison.Ordinal);
if (areEqual == false)
{
//Show do not match errors is password is not blank and is not invalid format
if (IsPasswordBlank == false && IsPasswordValid == false)
{
cvPasswordValidation.ErrorMessage = "Your passwords do not match.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
}
and the .ascx:
<asp:TextBox runat="server" ID="txtPassword" MaxLength="12" autocomplete="off" TextMode="Password" ValidationGroup="vgOnlineDetails"></asp:TextBox>
<asp:CustomValidator ID="cvPasswordValidation"
runat="server"
display="Dynamic"
OnServerValidate="cvPasswordValidation_ServerValidate"
ControlToValidate="txtPassword"
ValidationGroup="vgOnlineDetails">
</asp:CustomValidator>
You need to set ValidateEmptyText = true to validate empty fields.
You shoul use return after assignment to IsValid property. Condider situation when you do not specify password at all. If you do not specify return after assignment all three if statements will be executed. In last if areEqual variable will be true because two empty strings are equal and cvPasswordValidation.IsValid = true; will be executed. In this case your text boxes will be valid.

Categories