I'm trying to turn on/off various RequiredFieldValidator controls when checkboxes are checked/unchecked, based on this question. But rather than having a separate js function for each checkbox I want to pass in the ClientID of the input to validate, something like this (only one INPUT here but you can see once it's working I can add more INPUTs without more js):
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClick="updateValidator('<%= rfvSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
Currently that scriptlet txtSubject.ClientID isn't evaluated, just output directly. I'm sure this is simple but I just don't know the appropriate syntax.
How about adding it via the codebehind (or a script section):
checkSubjectRequired.Attributes.Add("onclick", "updateValidator(" +
txtSubject.ClientID + ")");
This explaination of ClientID may be helpful.
This is because; ASP.NET parser can not parse server tag "<% = %>" for a server side control (i.e. control made as runat='server').
Use the following:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClick="updateValidator('<%#txtSubject.ClientID %>');" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
You could just do this:
<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server"
OnClientClick="updateValidator(this.id);" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject"
ErrorMessage="You must enter a subject." runat="server" />
<script>
function updateValidator(inputId) {
var enableValidator = !event.srcElement.checked;
var theInput = document.getElementById(inputId);
ValidatorEnable(theInput, enableValidator);
}
</script>
Related
I am tring to Create a Comment box having reply option for my Website
Below Is My aspx page
<div>
<asp:Repeater runat="server" ID="repAnswer">
<ItemTemplate>
<h6>Answer</h6>
<p><%# Eval("Answer") %></p>
<asp:Label runat="server" ID="lblAnsId" Text='<%# Eval("AnsId")%>' Visible="false"></asp:Label>
<a class="link" id='lnkReplyParent<%#Eval("AnsId") %>' href="javascript:void(0)" onclick="showReply(<%#Eval("AnsId") %>);return false;">Reply</a>
<a class="link" id="lnkCancle" href="javascript:void(0)" onclick="closeReply(<%#Eval("AnsId") %>);return false;">Cancle</a>
<div id='divReply<%#Eval("AnsId") %>' style="display:none;">
<asp:TextBox ID="textCommentReplyParent" CssClass="input-group" runat="server" Width="300px" TextMode="MultiLine" ></asp:TextBox>
<br />
<asp:Button ID="btnReplyParent" runat="server" Text="Reply" OnClick="btnReply_Click" /></div>
</ItemTemplate>
</asp:Repeater>
</div>
<div style="margin-top:100px">
<h5>Your Answer</h5>
<hr />
<CKEditor:CKEditorControl ID="txtAddAnswer" BasePath="Admin/ckeditor/" runat="server">
</CKEditor:CKEditorControl>
<asp:Button runat="server" ID="btnAnswer" Text="Submit Answer" OnClick="btnAnswer_Click"/>
</div>
i have used Repeater to bind my answer or comment. Inside the repeater i have given two link pne is of reply other is of cancel.when someone click on the reply a new textbox and button open which is used to give the reply
Below is my cs page
protected void btnReply_Click(object sender, EventArgs e)
{
foreach (RepeaterItem row in repAnswer.Items)
{
Label lblNewAnsIdholder = (Label)row.FindControl("lblNewAnsIdholder");
TextBox txtReplyToAnswer = (TextBox)row.FindControl("txtReplyToAnswer");
OnlineSubjects onlinesub = new OnlineSubjects()
{
reply = txtReplyToAnswer.Text.Trim(),
AnsId = Convert.ToInt32(lblNewAnsIdholder.Text.ToString())
};
onlinesub.addAnswer();
}
}
i dont know how to use textbox in repeater but after searching it through google i get something like this which i am not sure thats right or wrong.
And the line where i have created my object for my class i am getting error from there
I am tring to pass the value of textbox as a paramter
Plz help me to do this.
Thank You
You Should try,
TextBox txtReplyToAnswer = ((TextBox)row.FindControl("txtReplyToAnswer")).Text;
Hope this will work.
I have a dropdown list that when selected value is equal to "Closed". I want a Required field to become enabled. I have tried this
<asp:DropDownList ID="DropDownList9" runat="server"
DataSourceID="SqlDataCaseStatus" DataTextField="CaseStatus"
DataValueField="CaseStatus" Text='<%# Bind("Case_Status") %>' AutoPostBack="False" onchange="if(this.options[this.selectedIndex].text='Closed')ValidatorEnable('RequiredFieldValidatorDateOfWriteOff', true);else ValidatorEnable('RequiredFieldValidatorDateOfWriteOff', false); " >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorDateOfWriteOff" runat="server"
ControlToValidate="TextBox13"
ErrorMessage="Date Of Write Off is a Required Field">*</asp:RequiredFieldValidator>
But when i change the dropdown i get an error:
Microsoft JScript runtime error: Unable to set value of the property 'visibility': object is null or undefined.
any help would be much appreciated
First of all try changing = to == when comparing text with 'Closed'.
You need to use the Enabled property. Give this a go, the code is very rough and is just for an example. I have extracted the behaviour into one method, just for ease of demonstration.
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function EnableValidator() {
var dropdown1 = document.getElementById('DropDownList1');
var a = dropdown1.options[dropdown1.selectedIndex];
if (a.text == "ValidateYes1") {
document.getElementById("RequiredFieldValidator1").enabled = true;
} else {
document.getElementById("RequiredFieldValidator1").enabled = false;
}
};
</script>
<div>
</div>
<asp:DropDownList ID="DropDownList1" runat="server" onchange="EnableValidator();">
<asp:ListItem>ValidateYes1</asp:ListItem>
<asp:ListItem>ValidateNo2</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator><asp:Button
ID="Button1" runat="server" Text="Button" />
</form>
</body>
ValidatorEnable requires control and you are passing id of control
ValidatorEnable('RequiredFieldValidatorDateOfWriteOff', true)
That is why you are getting the object null error.
Please change it to
ValidatorEnable(document.getElementById('<%= RequiredFieldValidatorDateOfWriteOff.ClientID %>'), true);
<asp:DropDownList ID="DropDownList9" runat="server"
DataSourceID="SqlDataCaseStatus" DataTextField="CaseStatus"
DataValueField="CaseStatus" Text='<%# Bind("Case_Status") %>' AutoPostBack="False" onchange="validateSelection(this);" >
</asp:DropDownList>
<script language="javascript" type="text/javascript">
function validateSelection(drp) {
var vc = document.getElementById('<% = RequiredFieldValidatorDateOfWriteOff.ClientID %>');
if (drp.text == 'Closed') {
ValidatorEnable(vc, true);
}
else {
ValidatorEnable(vc, false);
}
}
</script>
I am using below .aspx code to validate textbox..this is working perfectly
<asp:TextBox ID="tbnooflecture" runat="server" Width="113px" Height="33px">
</asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ForeColor="#6600FF" runat="server"
ErrorMessage="Total Attendence Should be Like 3 or 50"
ValidationGroup="upper" Display="Dynamic"
ControlToValidate="tbnooflecture"
ValidationExpression="[0-9][0-9]|[0-9]">*
</asp:RegularExpressionValidator>
What I want that above this textbox there is dropdownlist named batchname and if length of batchname is 2, I want to put validation that Attendence should be even no.
I have used below code on button click
if (lenghth == 2)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(name, "[1-9][02468]"))
{
Label5.Text = "Only Even Entry for Labs";
Label5.Visible = true;
}
}
I want to do it on client-side. How can I do it in C#?
You need to use custom-validation control of asp.net.
Few useful links
https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx
http://msdn.microsoft.com/en-us/library/f5db6z8k%28v=vs.71%29.aspx
http://www.w3schools.com/aspnet/control_customvalidator.asp
Custom validator error text through javascript?
That is server side validation #user2053138, you mentioned in comment.
Check out the following example:
<asp:TextBox id="Text1"
runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<script language="javascript">
function ClientValidate(source, arguments)
{
if (arguments.Value % 2 == 0 ){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
I have a radiobuttonlist with three choices. When a user clicks on the "Provided" option, two textboxes open underneath it. These two are required when selecting that option. How can I require these two only when that option is marked but not if it isn't and still allow me to process the form? I tried using ValidationGroup, but since I am still new to developing, I think I am missing something. Any guidance would be appreciated, thanks in advance!
<asp:RadioButtonList ID="rblCreat" runat="server" RepeatDirection="Horizontal" CssClass="rblMargin rblCreat">
<asp:ListItem>N/A</asp:ListItem>
<asp:ListItem>DIC to Obtain</asp:ListItem>
<asp:ListItem>Provided</asp:ListItem>
</asp:RadioButtonList>
<div style="display: none;" id="provided-fields">
<br />
<p style="margin-left: 250px">
Results:
<asp:TextBox ID="txtCreatResults" runat="server" Width="99px" TabIndex="21" Height="22px"
CssClass="margin"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvResults" runat="server" ControlToValidate="txtCreatResults"
ErrorMessage="*Required" ValidationGroup="provided"></asp:RequiredFieldValidator>
<br />
Date:
<asp:TextBox ID="txtCreatDate" runat="server" Width="99px" TabIndex="22" onkeydown="return DateFormat(this, event.keyCode)"
Height="22px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDate" runat="server" ControlToValidate="txtCreatDate"
ErrorMessage="*Required" ValidationGroup="provided"></asp:RequiredFieldValidator>
</p>
</div>
Your code Behind
protected void Page_Load(object sender, EventArgs e)
{
rblCreat.Items[0].Attributes.Add("onclick", "abc('1');");
rblCreat.Items[1].Attributes.Add("onclick", "abc('2');");
rblCreat.Items[2].Attributes.Add("onclick", "abc('3');");
}
Your Java Script
<script language="javascript" type="text/javascript">
function abc(ID) {
if (ID == '3') {
var btn = document.getElementById("<%=btn.ClientID%>");
btn.onclick = function () {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btn.id, "", true, "provided", "", false, false));
}
document.getElementById('providedfields').style.display = 'block';
}
if (ID == '1' || ID == '2') {
var btn = document.getElementById("<%=btn.ClientID%>");
btn.onclick = function () {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btn.id, "", true, "newValGroup", "", false, false));
}
document.getElementById('providedfields').style.display = 'none';
}
}
</script>
Your HTML
<asp:radiobuttonlist id="rblCreat" runat="server" repeatdirection="Horizontal" cssclass="rblMargin rblCreat">
<asp:ListItem Value="1">N/A</asp:ListItem>
<asp:ListItem Value="2">DIC to Obtain</asp:ListItem>
<asp:ListItem Value="3">Provided</asp:ListItem>
</asp:radiobuttonlist>
<div style="display: none;" id="providedfields">
<br />
<p style="margin-left: 250px">
Results:
<asp:textbox id="txtCreatResults" runat="server" width="99px" tabindex="21" height="22px"
cssclass="margin"></asp:textbox>
<asp:requiredfieldvalidator id="rfvResults" runat="server" controltovalidate="txtCreatResults"
errormessage="*Required" validationgroup="provided"></asp:requiredfieldvalidator>
<br />
Date:
<asp:textbox id="txtCreatDate" runat="server" width="99px" tabindex="22" height="22px"></asp:textbox>
<asp:requiredfieldvalidator id="rfvDate" runat="server" controltovalidate="txtCreatDate"
errormessage="*Required" validationgroup="provided"></asp:requiredfieldvalidator>
</p>
</div>
<asp:button id="btn" validationgroup="provided" runat="server" />
When you click on the button it will postback in case of other then provided options.
I believe a CustomValidator could help you with this.
<asp:CustomValidator
runat="server"
id="cusCustom"
controltovalidate="txtCreatDate"
onservervalidate="cusCustom_ServerValidate"
errormessage="You must enter a text." />
and then write the method in your code behind with whatever logic you might need.
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (rblCreat.SelectedIndex == 1)
{
if (e.Value.Length > 0)
{
e.IsValid = true;
}
else
{
e.IsValid = false;
}
}
else {
e.IsValid = true;
}
}
Note: This is not written in any IDE so I can't be sure about the syntax.
Before processing the form, you could check (from the server code) whether the required option in the radiobuttonlist is checked. If not, set the Enabled property of the requiredfieldvalidators to False.
I have an AJAX ToolKit TabContainer control with several TabPanels. I want to validate the contents of the current active TabPanel to prevent user from working on other ones in case data was invalid.
If you need to do a TabPanelChangingEvent SERVER side, You will need to do this by Altering the ajaxcontroltoolkit Source code.
Good news : you could easily get it
Here a new solution that does almost what your need :
The OnClientActiveTabChanged event is raised
The tabcontainer New Tab index is saved in a Hiddenfield
The tabindex is reset to it's old value (so it wont change right now)
The form trigger a asyncpostback using a hidden button.
Within the hidden button's Click event, the OldTabIndex and NewTabIndex are retrieved.
At the end of the Click event, the tabcontainer's tabindex is switched to the new value.
So, the hidden button's Click event is executed before the TabContainer tab is changed.
aspx:
<asp:Button runat="server" ID="hiddenTargetControlForTabContainer" style="display:none" />
<asp:UpdatePanel ID="TabContainerUpdatePanel" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="hiddenTargetControlForTabContainer" />
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="TabContainerActiveTab" runat="server" Value="0" />
<AjaxControlToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"
OnClientActiveTabChanged="OrderTabContainerClientActiveTabChanged" >
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel1"
HeaderText="TabPanel1"
>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel2"
HeaderText="TabPanel2" >
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
</AjaxControlToolkit:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
var TabContainerActiveTabControlID = '<%= TabContainerActiveTab.ClientID %>';
var hiddenTargetControlForTabContainerControlID = '<%= hiddenTargetControlForTabContainer.uniqueID %>';
function OrderTabContainerClientActiveTabChanged(sender, args) {
var TabContainerActiveTabControl = $get(TabContainerActiveTabControlID);
var OldtabIndex = parseInt(TabContainerActiveTabControl.value);
var NewtabIndex = sender.get_activeTabIndex();
if (!(OldtabIndex == NewtabIndex)) {
sender.set_activeTabIndex(OldtabIndex);
TabContainerActiveTabControl.value = NewtabIndex;
__doPostBack(hiddenTargetControlForTabContainerControlID, '');
}
}
Code behind:
Protected Sub hiddenTargetControlForTabContainer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles hiddenTargetControlForTabContainer.Click
Dim oldActiveTabIndex = TabContainer1.ActiveTabIndex
Dim newActiveTabIndex As Integer = Convert.ToInt32(TabContainerActiveTab.Value)
'your stuff here
TabContainer1.ActiveTabIndex = newActiveTabIndex
End Sub
Problem: Ajax TabContainer the ActiveTabChanged event shows incorrect ActiveTabIndex.
For eg. TabContainer contain 3 tabs, if second tab is hide(visible = false on server side) then on click of third tab, we get ActiveTabChanged = 1 not 2 (expected active index is 2 on server side code).
Solution:
Register the clientside event of the tab container:
OnClientActiveTabChanged="Tab_SelectionChanged"
Then define the javascript function to handle the above event which will internally store the tab index in a hidden variable.
function Tab_SelectionChanged(sender,e)
{
document.getElementById('<%=hdntabIndex.ClientID %>').value = sender.get_activeTabIndex();
}
Use the hidden variable(hdntabIndex) in the code behind where ever you need the active tab index.
You should do it using JavaScript.
Here an example I made, the trick is to use ValidationGroup and save the Old tab Index at the end of the function called by the OnClientActiveTabChanged
<AjaxControlToolkit:TabContainer ID="TabContainer1" runat="server" Height="138px"
Width="402px" ActiveTabIndex="0"
OnClientActiveTabChanged="ValidateTab" >
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel1"
HeaderText="TabPanel1"
>
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="TextBox1"
ValidationGroup="TabPanel1"
/>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
<AjaxControlToolkit:TabPanel runat="server" ID="TabPanel2"
HeaderText="TabPanel2" >
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ErrorMessage="RequiredFieldValidator"
ControlToValidate="TextBox2"
ValidationGroup="TabPanel2"
/>
</ContentTemplate>
</AjaxControlToolkit:TabPanel>
</AjaxControlToolkit:TabContainer>
<script type="text/javascript">
var OldtabIndex = 0;
function ValidateTab(sender, args) {
if (OldtabIndex == 0) {
if (!Page_ClientValidate('TabPanel1')) {
sender.set_activeTabIndex(OldtabIndex);
}
}
else if (OldtabIndex == 1) {
if (!Page_ClientValidate('TabPanel2')) {
sender.set_activeTabIndex(OldtabIndex);
}
}
OldtabIndex = sender.get_activeTabIndex();
}
</Script>
I know I'm probably late to answering this question, but hopefully, I can offer some assistance to someone who's pot-committed like I was to the TabPanels.
Add the OnClientActiveTabChanged="showMap" to the ajaxToolkit:TabContainer. My function is obviously called showMap (had to hide and show the Google Street Map, because TabContainer screws it all up. So I had to move the Google Street Map outside of the container and then 'fake' put it back in the container).
<ajaxToolkit:TabContainer runat="server" ID="tabs" OnClientActiveTabChanged="showMap">
<ajaxToolkit:TabPanel runat="server" ID="pnlZones" HeaderText="Delivery Zones">
<ContentTemplate>
...
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
Then create the javascript:
<script type="text/javascript">
function showMap() {
var tabID = $('.ajax__tab_active').attr('id');
if (tabID.indexOf('pnlZone') > 0) {
$('#mapHider').css('height', '600px');
}
else {
$('#mapHider').css('height', '0');
}
}
</script>
We can then find the active tab by the class .ajax__tab active, which is what TabContainer will set the active class to. Snag the ID (.attr('id')) with jQuery... And voila, we now which tab we're currently on.
For this I change the height of the class from 0 to 600px. With the overflow set to hidden, it makes it seem like the map is on the page and only in that container, but it isn't.
Hopefully, this helps!! Good luck.