Validating user controls regardless of page controls - c#

I want to validate my user control whenever postback occurs. This is the property inside usercontrol wish I want to validate:
public string Text
{
get
{
return DateTextBox.Text;
}
set
{
DateTextBox.Text = value;
}
}
The Text Property always must have format like "YYYY/MM/DD". I want wherever user add this control to every page, when user submits any button, if the Text is not valid, button submit event does not raise. The main problem is that i want this works without altering any page. I means without checking something like Page.IsValid.

You can do this by adding ASP.Net validation controls to your .ascx markup code.
Try adding the following code
<asp:CompareValidator
id="dateValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="DateTextBox"
ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
ControlToValidate="DateTextBox"
runat="server"
ErrorMessage="Required!">
</asp:RequiredFieldValidator>
But, the problem with this method is all buttons (Save or Submit) not having CauseValidation=False will try to validate this TextBox.
To overcome this issue you need to
If buttons are in the user control add a ValidationGroup to all controls (TextBox, Validation controls, buttons etc)
If buttons are in your pages
add a public property to your control to hold the ValidationGroup and assign this value to all controls and all the buttons that need to validate.

Try below code:-
public string Text
{
get
{
return DateTextBox.Text;
}
set
{
try
{
DateTime d = DateTime.ParseExact(value, "yyyy/MM/dd",CultureInfo.InvarientCulture);
DateTextBox.Text = value;
}
catch(Exception ex)
{
//// Code when it does not match format.
}
}
}

Related

How to dynamically load a text into a user control label in asp.net?

I want to load 2 user controls(same but with different text property).
My user control consists of a label with a Function defined for text in ascx.cs
i am loading the control at run time using a panel ..here i want both the user control label to have different texts.
My .ascx file
<asp:Label ID="uclbl" runat="server" />
My .ascx.cs file
public string textforlabel
{
get { return uclbl.Text; }
set { uclbl.Text = value; }
}
My .aspx file
<asp:Panel ID="panelMain" runat="server" >
</asp:Panel>
* i have registered the the control
My .aspx.cs file
Control _dummyUserControl = (Control)Page.LoadControl("~/UserControl/User1.ascx");
_dummyUserControl. ; //can not find the textforlabel here
panelMain.Controls.Add(_dummyUserControl);
because you are making incorrect casting, you should cast to your user control type :
User1 _dummyUserControl = (User1)Page.LoadControl("~/UserControl/User1.ascx");
_dummyUserControl.MyProperty = "SDfsdf" ; //here you can find all your custom properties
panelMain.Controls.Add(_dummyUserControl);
You have to type cast:
User1 _dummyUserControl = (User1)Page.LoadControl("~/UserControl/User1.ascx");

Unable to read hidden field value in ascx.cs page

I have a hidden field like this:
<asp:HiddenField ID="showHideFlag" runat="server" />
I am assigning some value to this hidden field in java script as follows:
function controlSearchBar() {
if ($("#MainContent_ProjectListControl_searchBar").is(":hidden")) {
$("#MainContent_ProjectListControl_showHideFlag")[0].value = "showing";
} else {
$("#MainContent_ProjectListControl_showHideFlag")[0].value = "hiding";
}
}
I am trying to read this hidden field in ascx.cs page as follows:
string hdnValue = this.showHideFlag.Value;
But this hdnValue is not getting the value of that hidden field.
Can someone help on this?
Hidden as type="hidden"
$("#MainContent_ProjectListControl_searchBar").attr('type') == 'hidden'
Hidden as display: none
$("#MainContent_ProjectListControl_searchBar").is(":hidden")
Gets the control ID for HTML markup that is generated by ASP.NET.
<asp:Label ID="SelectedSport" runat="server" ClientIDMode="Static" ClientID="showHideFlag">
javascript
$("#showHideFlag").text("found");
You are saying that you can get the value in javascript So I think the the problem is with the hidden field. try to set value by Client id as follows-
var hd = document.getElementById('<%= showHideFlag.ClientID%>');
hd.value = "hi";
And my another question is in which event you are accessing value? because If you are setting value in javascript and accessing in Page Load event then it will not work because first of all Page load event gets fired and then Javascript function executes.

ASP/C# TextBox Validation

I need to create a webform where users can add, update, delete, retrieve customer data from a table in an SQL database.
Should have textboxes for each field in the table so that the users can enter details of the fields to update the table in the DB.
What im having trouble with is in the code behind the form i need to make a clear method to clear all the textboxes and the message label.
I also need to set validation requirements for each textbox. But i am unsure how to do this properly.
The textboxes are;
CustID, Firstname, Surname, Gender, Age, Address1, Address2, City, Phone, Mobile, Email, Confirm Email.
Now my main question is, how do i validate the textboxes? For example;
CustID is required. & Must be unique. Must be an integer and must be between 1 & 1000.
You should use RequiredValidator for example
http://www.w3schools.com/aspnet/control_reqfieldvalidator.asp
This will perform validation before submitting data to server ;)
There are also other type of validator, like RangeValidator (for the need to check if the integer is between 1 and 1000).
Example:
<asp:RangeValidator ControlToValidate="youtField" MinimumValue="1" MaximumValue="1000" Type="Integer" Text="The field must be between 1 and 1000" runat="server" />
You can also add a ValidationGroup="save" for example to all your validators and to the button that user should click to save and update data.
Asp.net Have some (5 main types) server validation control's , You can use the validations for your requirement
See this image for understanding validation controls (The image referred from )
More understanding by this MSDN sit3
and here is link for all validation control sample's : click me
Here could be an example for ASP/ MVC - because you have forgotten to specify which technology from ASP. Forms or MVC ?!?
This bellow aplies to mvc and the other attributes are allready defined by the users before me.
Note that the RemoteAttribute can verify a function (validation function) .
namespace ModelValidation.Models {
public class Appointment {
[Required]
[StringLength(10, MinimumLength = 3)]
public string ClientName { get; set; }
[DataType(DataType.Date)]
[Remote("ValidateDate", "Home")]
public DateTime Date { get; set; }
public bool TermsAccepted { get; set; }
}
}
To apply validation on a model property that describes a TextBox, then a good proactice is to use TextBoxFor<>(). Like that:
#Html.TextBoxFor((model) => model.ClientName )
You can clear all your controls values by either redirecting to user to another page telling him that form is submitted, New Registration button to redirect user again to Registration page, However if you don't want that you can pick up each control and reset them either in Cs.file or using javascript,
foreach (Control ctrl in form1.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.Text = string.Empty;
}
else if (ctrl is DropDownList)
{
DropDownList dl = (DropDownList)ctrl;
dl.SelectedIndex = 0;
}
else if (ctrl is CheckBox)
{
CheckBox cb = (CheckBox)ctrl;
cb.Checked = false;
}
}
For your validation purpose i strongly suggest you to read about validation in Asp.net , here is a good tutorial you can learn from here
To clear all textbox you can try something like this
foreach (var item in Page.Controls)
{
if (item is TextBox)
{
((TextBox)item).Text = "";
}
if (item is DropDownList)
{
((DropDownList)item).SelectedIndex= 0;
}
//and the other types
}
For the part of validation you have to set the validation fields that you desire and bind it to the field directly on the .aspx page
<asp:textbox ID="Name" runat="server" TabIndex="1"/>
<asp:RequiredFieldValidator ID="rfvName" ControlToValidate="Name" runat="server" ErrorMessage="Name is required">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
When you try to save and one of the condition of your validators returns false, the validation summary will show all the errors written in the errormessage attribute.

How to bind ASP TextBox's Text to its ToolTip?

I would like to the ToolTip always be the same as the ASP TextBox's Text. Of course I can write
AnyTextBox.Text = "any text";
AnyTextBox.ToolTip = "any text";
but I do not want to duplicate hundreds of assignment statements.
I also could write change event handlers for the Text property, but I do not want to write dozens of event handlers just for this (if there is a more elegant solution)
Is there? Something like this:
<asp:TextBox ID="AnyTextBox" runat="server" ToolTip="binding magic goes here, but how?">
Thx in advance
You could write your own custom control which inherits from TextBox? I used the Text property to set the tooltip, but you can do it the other way around if you want.
Control:
public class TooltipTextBox : TextBox {
public new string Text {
get { return base.Text; }
set
{
base.Text = value;
this.ToolTip = value;
}
}
}
Markup:
<my:TooltipTextBox ID="AnyTextBox" runat="server" Text="binding magic goes here">
As far as i know there is no such automatism. For what it's worth, maybe you can use PreRender:
protected void Page_PreRender(Object sender, EventArgs e)
{
var allTextControlsWithTooltips = new List<WebControl>();
var stack = new Stack<Control>(this.Controls.Cast<Control>());
while (stack.Count > 0)
{
Control currentControl = stack.Pop();
if (currentControl is WebControl && currentControl is ITextControl)
allTextControlsWithTooltips.Add((WebControl)currentControl);
foreach (Control control in currentControl.Controls)
stack.Push(control);
}
foreach (var txt in allTextControlsWithTooltips)
txt.ToolTip = ((ITextControl)txt).Text;
}
You could also use a UserControl which handles this event, then you just need to put it on all of the pages that should behave in this way. Or you could let all pages inherit from one base page.
I think using a JavaScript event handler will be your easiest solution. You don't need to write hundreds of event handlers though. Just write one and then use that same event handler for all your text boxes!
<asp:TextBox ID="AnyTextBox" runat="server" onchange="setTooltip(this)" />
And then the script would be
function setTooltip(textbox) {
textbox.title = textbox.value;
}
That's it! Set that onchange event for all your Textboxes who you want to have this tooltip behavior.
You can do this in the TextChanged event of the textbox :
<asp:TextBox ID="AnyTextBox" runat="server" TextChanged="AnyTextBoxTextChanged">
protected void AnyTextBoxTextChanged(object sender, EventArgs e)
{
this.AnyTextBox.Tooltip = this.AnyTextBox.Text;
}
That depends if you are looking for "live update" of tooltip = i.e. do you want to change the tooltip when the user changes the text on website? Then use "onchange" event of the input and JS function that would change its "title" attribute on each event call.
Or you want to ease of your server-side work and do not want to specify tooltip and text for each item, then go with custom control way (and I recommend RGraham code).
Or match both methods and use custom control that would also provide JS "refresh" code :-)
Try using jquery
$(function () {
var maybe = true;
var text = $('.myTextBox').val();
if (maybe) {
$('.myTextBox').attr('title', text);
}
});

Multipe validation control on single textbox

I have following code snippet in asp.net In which I am validating a Textbox.I have added two validation control in which first validate the format of date and second validates the future data.
Now the problem is both validations fire at the same time.
I want that first it's check that date is valid or not then I want to fire rangevalidator.
<asp:TextBox Enabled="True" runat="server" size="8" MaxLength="10" meta:resourcekey="txtTravelerDOBResource2">mm/dd/yyyy</asp:TextBox>
<asp:RangeValidator ID="rangeValidator" ControlToValidate="txtTravelerDOB" MaximumValue="09/25/2013" MinimumValue="1/1/2012" Type="Date" ErrorMessage="Future Date Not allowed" runat="server"></asp:RangeValidator>
<asp:RegularExpressionValidator Enabled="True" ID="rgxDOB" runat="server" ControlToValidate="txtTravelerDOB"
Display="Dynamic" ErrorMessage="Date is not valid"
ValidationExpression="^(((0?[13578]|1[02])[\/](0?[1-9]|[12]\d|3[01])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[13456789]|1[012])[\/](0?[1-9]|[12]\d|30)[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/](0?[1-9]|1\d|2[0-8])[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/]29[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))$"
></asp:RegularExpressionValidator>
I tried to enable disable the validation control using javascript as below.
function isGoodDate(){
var value=$("#ctl09_ctl00_ctl00_ctl00_rptTravelers_ctl01_txtTravelerDOB").val();
var v=$("#ctl09_ctl00_ctl00_ctl00_rptTravelers_ctl02_txtTravelerDOB").val();
var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
console.log(value);
if(reGoodDate.test(value))
{
$.each(Page_Validators, function (index, validator){
if (validator.validationGroup == "x"){
ValidatorEnable(validator, true);
}
});
}
else
{
ValidatorEnable(validator, false);
}
if(reGoodDate.test(v))
{
$.each(Page_Validators, function (index, validator){
if (validator.validationGroup == "y"){
ValidatorEnable(validator, true);
}
});
}
else
{
ValidatorEnable(validator, false);
}
}
Firstly, all the validators don't fire exactly at same time. They seem so as it happens in a fraction of seconds.
The validators that you add in a .aspx page, they are added to Page.Validators collection in the same order they are created/added to page. The validation runs in the order they are present in the Page.Validators collection.Thus the first validator in the aspx file is first in Page.Validators. If you want to rearrange the order, then the correct way is to arrange your validators in the page in the same order you want them to fire.
NOTE: The validators will fire one by one. in case you don't want the very next validators to fire you may use Javascript to disable the next ones. call a ClientValidation function in first validator
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox3"
ClientValidationFunction="disableNextVal" .... />
// Sample JavaScript code
function disableNextVal()
{
// firstly check here for first condition, if First condition fails,
// disable the next validator as below.
var nextVal = document.getElementById('nextValidatorClientID');
ValidatorEnable(myVal, false);
// or use this one:
myVal.enabled = false;
}
However, one more solution and possibly the better one is mentioned below.
In these scenarios where the value entered in TextBox should pass multiple conditions like:data format, Value should be greater than some minimum required value etc.. it is always good to use a CustomValidator control.
In this custom validator control check one by one each of your conditions. If first condition fails: date is not valid, do not check others and display the error message for first one only. Similarly, if second condition fails: range is not valid, display message for second failed condition only.
<asp:CustomValidator ID= "valxTextBox" runat="server"Enabled="true"
ControlToValidate="txtDate"
ClientValidationFunction ="ValidateTxtDate"
ValidateEmptyText="true"
OnServerValidate="valxTextBox_ValidatePostalCode"
></asp:CustomValidator>
As you see, this gives the flexibility to define your custom Client Side as well as server side events for Validation.
In your server validation, check for conditions one by one, and return as soon as you find one failing.
For validating data against regularExpressions, use Regex class of System.Text.RegularExpressions namespace.
protected void valeEmailAddress_txtEmailAddressValidate(object sender,
ServerValidateEventArgs e)
{
string MaximumValue="09/25/2013";
string MinimumValue="1/1/2012";
// check for first condition
if(txtTravelerDOB >MaximumValue ||txtTravelerDOB < MinimumValue )
{
// sample code here
// if failing, set IsValid to false
e.IsValid = false;
// dynamically set the error message as per first condition
valxTextBox.ErrorMessage ="Not a valid date";
}
// check for second condition
// read the expression pattern from appSettings
if(!Regex.Match(txtTravelerDOB.Text.Trim(),
WebConfigurationManager.AppSettings("travelerDOBRegEX")).Success)
{
// if fails,
e.IsValid = false;
valxTextBox.ErrorMessage ="Format is Invalid";
}
}
Appsettings Value:
<add key="travelerDOBRegEX" value="^(((0?[13578]|1[02])[\/](0?[1-9]|[12]\d|3[01])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[13456789]|1[012])[\/](0?[1-9]|[12]\d|30)[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/](0?[1-9]|1\d|2[0-8])[\/]((1[6-9]|[2-9]\d)?\d{2}))|(0?2[\/]29[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))$"/>

Categories

Resources