How to validate special character entry in any controls within a page? - asp.net

I have designed a page where user can write messages and send within a group but i want that if they enter any special character like <>?## etc a msg should be displayed irrespective of the crashing of the page.
Can anyone help me out???

for that you have to use javaScript validation or any server site validation
for javaScript
function validate(inputText)
{
if(inputText.match(/[<>]/))
return false;
}
function TextBoxValidate()
{
var txt1=document.getElementById(TextBoxId).value;
if(!(validate(inputText)))
{
alert("incorrect text")
return false;
}
else
return true;
}
call these function in that text box where you want to validate by using onClientClick="return TextBoxValidate();"

You have 2 possibilities for doing that.
A) You are adding a regularexpression validator to each control
B) You use a customvalidator which you can bind to each control too
First solution is the better one for you.
How you do it? See here: http://www.codeproject.com/KB/validation/aspnetvalidation.aspx

It's not reccommended but you can use ValidateRequest="false" in the page declaration to allow values like that to be sucessfully posted back.
e.g. <%# Page Title="" Language="C#" ValidateRequest="false"..

Related

I have grid and hyperlink column inside it. How to prevent redirect if come condition is true?

This hyper link column show some counters. And if count is 0 i write "N/A" inside this column. I need transform this cell from hyper link to regular text or maybe something else. Main idea of this, this field should not look like hyperlink.
To make the hyperlink to not follow the link, you must return false on the javascript event onclick
On the asp.net you can do that as:
<asp:Hyperlink runat="server" OnClientClick="return CanIGo();" />
and with javascript
<script>
function CanIGo()
{
if(contitionToAllowClick)
return true;
else
return false;
}
</script>
The rest part of the user interface is left to you. You can show a message, change the style and make it look as text, or what ever you like.

Compare validation for two custom control

I have scenario, Page contains Check in date and Check out date for input. I used user control for datepicker, so both dates are called same user control.
Like,
Check In Date: <uc:datepicker ID="CheckInDate" runat="server" />
Check Out Date: <uc:datepicker ID="CheckOutDate" runat="server" />
Now I do validation for both dates which should not be blank like.
public class CustomiseDatePickerValidator : BaseValidator
{
protected override bool EvaluateIsValid()
{
Control c = this.FindControl(this.ControlToValidate);
DatePicker datepickerSelected = c as DatePicker;
ICustomiseRadDatePicker additionUserControl = (ICustomiseRadDatePicker)c.Parent;
if (string.IsNullOrEmpty(datepickerSelected.DateInput.Text))
{
return false;
}
return true;
}
}
This is working fine but I want also compare both datepicker value So Check in date Should be less than Check out date
It would probably be easier to use a CustomValidator for this. With the CustomValidator, you can specify your own client-side validation logic.
See this question for more details:
ASP.NET Custom Validator Client side & Server Side validation not firing
I may be wrong, but i think you need to use a CompareValidator for this. Correct me if i am missing something
A better solution to a CustomValidator is to apply the ValidationPropertyAttribute to the user control class. That way you can use normal ASP.NET validators against the user control as you would any other control.

Exclude Control from Page.Isvalid

I have a few controls on a page that are all in the same validation group. Depending on certain conditions, one of these controls can be set to visible=false (and the user wont be able to input anything into it). If this happens, is there a way to remove said control from the validation group? Code like this:
if(testControl.Visible==false) testControl.ValidationGroup="";
does nothing. Yet, if I remove the validationgroup from the aspx page like so:
<asp:RequiredFieldValidator ID="testControl" runat="server" validationgroup=""></asp:RequiredFieldValidator>
The page will validate. Is there a way around this?
Are you sure your code is being hit in the code-behind file? I mean, your control is really invisible when you check that condition?
if(testControl.Visible == false)
testControl.ValidationGroup = string.Empty;
Put a breakpoint in testControl.ValidationGroup=""; and see if the debugger stops there.
Where is the code above? It should be inside the PageLoad method for example.
Call Page.Validate("NameOfYourValidationGroup") after that code.
What is the problem here I think:
You're setting this testControl with Visible = False and then you post back to the server. When you do testControl.ValidationGroup = string.Empty it'll have no effect because it has already posted back to the server:
From MSDN:
TextBox..::.ValidationGroup Property
Gets or sets the group of controls for
which the TextBox control causes
validation when it posts back to the
server.
This way you should call this code testControl.ValidationGroup = string.Empty; when you hide your control setting it to Visible = false so that when the page loads again for the user the control won't be assigned to that ValidationGroup. Now, if you postback the page it should validate the way you want it.
Set testControl.CausesValidation = false too.
Does the following help?:
testControl.IsValid = true;
Use for ex. with:
Page.Validate();
// manual override of specific control
testControl.IsValid = true;
// Guard
if (! Page.IsValid) return; // Or do own custom logic
// else
// Do your stuff here...

How to set focus to a web control in ASP.NET

Question: What is the best way to set focus to a web control in ASP .NET.
I can do it, but it's ugly. I have a web control wrapped in a web control hosted on a web page. So, if you do a view | source on the page the id is something like WrapperControl_Control_TextBox.
I've tried the "tried and true" Javascript methods of grabbing the element and setting it's focus: document.getElementByID( "WrapperControl_Control_TextBox" ).focus(); and it didn't work. I'm not sure why.
I know I could possibly do:
document.getElementById( "<%= TextBox.ClientID %>" ).focus(); too, I think. This won't work because of another totally separate error based on the fact you can't dynamically add controls to a header if there is a "<% %>" in the page. GAH.
In the "bottom-most" control, I've tried setting the focus (TextBox.Focus() in Page_Load) and that doesn't work either.
Anyway, the way that works is by simply taking the ControlsCollection of the Page, grabbing the control I need from that, getting it's collection, grabbing the next lower control and so forth.
I only have to do this seven times. So I have eight foreach loops.
Basically, my code is like this:
///////////////////////////////
// On the page
///////////////////////////////
ControlCollection controls = Controls;
foreach( Control control in controls)
{
if ( string.Equals( control.ID, "FormID", StringComparison.InvariantCultureIgnore ) )
{
ControlCollection nextControls = control.Controls;
foreach( Control nextControl in nextControls )
{
if ( string.Equals( nextControl.ID, "DivICareAboutInTheForm", StringComparison.InvariantCultureIgnor ) )
{
ControlCollection nextNextControls = nextControl.Controls;
//:
//:
//Yes, it's that bad and so forth.
//:
//:
}
}
}
}
You can use jQuery to do a search for IDs that end with your textbox name. This way you wont have to call the UniqueID server-side code. Just make sure not to have multiple controls that end with the same name
<script type="text/javascript">
$(document).ready(function() {
$('[id$=txtBox]').focus();
});
</script>
Or, you can use a Class name for the default text box.
<asp:Textbox ID="txtBox" runat="server" cCssClass="defaultTextbox" />
jquery:
$('.defaultTextbox').focus();
You can get around the "cannot add dynamic controls because a <%= %> block exists on the page" error by changing the block to use databinding syntax: <%# TextBox.ClientID %>, and manually calling Page.DataBind() in Page_Load.
If you really want to use the Page_Load method, then you could always call the SetFocus method on the Page object.
Page.SetFocus(myTextBox);

Forcing TargetControl Textbox to use a value in the AutocompleteExtender

I'm sure I'm going to have to write supporting javascript code to do this. I have an autocomplete extender set up that selects values from a database table, when a selection is made, i would like it to set the ID of the value selected to a hidden control. I can do that by handling a value change on the text box and making a select call to the database, Select idCompany from Companies Where CompanyName = "the text box value";
The most important thing is to constrain the values of the text box that is the targetcontrol for the autocomplete extender to ONLY use values from the autocomplete drop down. Is this possible with that control, is there examples somewhere? is there a better control to use (within the ajax control toolkit or standard .net framework - not a third party control)?
I'm going to be trying to work out some javascript, but I'll be checking back to this question to see if anyone has some useful links. I've been googling this last night for quite a while.
Update: I did not get an answer or any useful links, I've posted an almost acceptable user control that does what I want, with a few workable issues.
No one was able to give me an answer. This has been an ongoing saga. It started when I was trying to find a solution not using drop down lists for large amounts of data. I have run into issues with this so many times in previous projects. This seems to be workable code. Now I need to know how to supply a AutoPostBack Property, and allow for some events, such as SelectedValueChanged. And due to the javascript, it will conflict with another control, if I have more than one of them on the same page. Well, that's some of the known issues I'm looking at with the code, but it's a start and definately better than looking at a hung browser for 3 or 4 minutes while the drop down is loading 30k list items.
This code is assuming there is an asmx file with the script methods GetCompanyListBySearchString and GetCompanyIDByCompanyName.
ASPX FILE
<%# Control Language="C#" AutoEventWireup="true" CodeFile="SelectCompany.ascx.cs" Inherits="Controls_SelectCompany" %>
<%# Register TagPrefix="ajaxToolkit" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %>
<script language="javascript" type="text/javascript">
var txtCompanyIDHiddenField = '<%= fldCompanyID.ClientID %>';
var txtCompanyIDTextBox = '<%= txtCompany.ClientID %>';
function getCompanyID() {
if (document.getElementById(txtCompanyIDTextBox).value != "")
CompanyService.GetCompanyIDByCompanyName(document.getElementById(txtCompanyIDTextBox).value, onCompanyIDSuccess, onCompanyIDFail);
}
function onCompanyIDSuccess(sender, e) {
if (sender == -1)
document.getElementById(txtCompanyIDTextBox).value = "";
document.getElementById(txtCompanyIDHiddenField).value = sender;
}
function onCompanyIDFail(sender, e) {
document.getElementById(txtCompanyIDTextBox).value = "";
document.getElementById(txtCompanyIDHiddenField).value = "-1";
}
function onCompanySelected() {
document.getElementById(txtCompanyIDTextBox).blur();
}
</script>
<asp:TextBox ID="txtCompany" runat="server" onblur='getCompanyID()'
/><ajaxToolkit:AutoCompleteExtender runat="server" ID="aceCompany" CompletionInterval="1000" CompletionSetCount="10"
MinimumPrefixLength="2" ServicePath="~/Company/CompanyService.asmx" ServiceMethod="GetCompanyListBySearchString"
OnClientItemSelected="onCompanySelected" TargetControlID="txtCompany" />
<asp:HiddenField ID="fldCompanyID" runat="server" Value="0" />
CODE BEHIND
[System.ComponentModel.DefaultProperty("Text")]
[ValidationProperty("Text")]
public partial class ApplicationControls_SelectCompany : System.Web.UI.UserControl
{
public string Text
{
get { return txtCompany.Text; }
set
{
txtCompany.Text = value;
//this should probably be read only and set the value based off of ID to
// make certain this is a valid Company
}
}
public int CompanyID
{
get
{
int ret = -1; Int32.TryParse(fldCompanyID.Value, out ret); return ret;
}
set
{
fldCompanyID.Value = value.ToString();
//Todo: should set code to set the Text based on the ID to keep things straight
}
}
}
Thanks for your post here. It is useful, however, it is assuming that everyone knows the setup to get the webservice called by a javascript function.
Sorry to be soo newbie, but I couldn't get the webservice called from client-side.
I read this documentation: http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
Furthermore, I found an interesting post that explains how to create/get a name value pair which is pretty much what you are expecting as far as I understood:
http://blogs.msdn.com/phaniraj/archive/2007/06/19/how-to-use-a-key-value-pair-in-your-autocompleteextender.aspx
Sorry if I misunderstood you, but I am just trying to guide other people that pass through the same situation.
Thanks a lot.
You can check the value of the selection by trapping on ClientItemSelected event and ensure that it is not blank.

Resources