Validation with one radio button option only - c#

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.

Related

Dropdown list enable required on textbox when selected value .net

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>

Show/Hide TextBox and enable/disable Textbox validation based on CheckBoxList selection

There is a CheckBoxList (selection can be multiple) and a TextBox which is not displayed by default. The requirements are:
1. When user click "Other" in CheckBoxList, the TextBox should display.
2. Since the TextBox is required when displayed, the Validator should be disabled when the TextBox is not displayed.
.aspx content page
<label for="labelSelection">Please Select:</label>
<asp:CheckBoxList ID="cblSelection" onclick="ShowOtherInfo(this)" runat="server">
<asp:ListItem Text="AAA" Value="1" />
<asp:ListItem Text="BBB" Value="2" />
<asp:ListItem Text="Other" Value="0" />
</asp:CheckBoxList>
<div id="OtherInfo" style ='display:none'>
<label for="labelOtherInfo">Enter detail if "Other" is selected: </label>
<asp:TextBox ID="OtherInfoTextBox" runat="server" />
<asp:RequiredFieldValidator ID="rfvOtherInfo" ControlToValidate="OtherInfoTextBox"
ErrorMessage="Enter other info" SetFocusOnError="true" Display="Dynamic" runat="server" />
</div>
<div>
<asp:Button ID="buttonSubmit" runat="server" Text="Submit" CausesValidation="true" OnClientClick="ShowOtherInfo()" OnClick="buttonSubmit_Click" />
</div>
Javascript placed on .master page
function ShowOtherInfo() {
var OI = document.getElementById('OtherInfo');
var CheckLists = document.getElementById('cblSelection');
var checkbox = CheckLists.getElementsByTagName("input");
if (checkbox[2].checked) {
document.getElementById('OtherInfo').style.display = "block";
ValidatorEnable(document.getElementById('rfvOtherInfo'), true);
} else {
document.getElementById('OtherInfo').style.display = "none";
ValidatorEnable(document.getElementById('rfvOtherInfo'), false);
}
}
Since I prefer using Javascript for validation, I have tried onchange/onclick event for CheckBoxList and onClientClick event for "Submit" button, but none of them works. Any help is greatly appreciated. After initial posting, I tried to replace OnSelectedIndexChanged="ShowOtherInfo" with onclick="ShowOtherInfo(this)" for CheckBoxList. And the code-behind on .cs file is:
public void DisplayOtherInfo(object sender, EventArgs e)
{
CheckBoxList cblSelection = (CheckBoxList)myFormView.FindControl("cblSelection");
RequiredFieldValidator rfvOtherInfo = (RequiredFieldValidator)myFormView.FindControl("rfvOtherInfo");
HtmlGenericControl OtherInfo = new HtmlGenericControl("OtherInfo");
for (int i = 0; i < cblSelection.Items.Count; i++)
{
if (cblSelection.Items[2].Selected == true)
{
OtherInfo.Style["display"] = "block";
rfvOtherInfo.Enabled = true;
}
else
{
OtherInfo.Style["display"] = "none";
rfvOtherInfo.Enabled = false;
}
}
}
But the TextBox still doesn't even display, not to say disable validator.
This is the Javascript Code
<script type="text/javascript">
function ShowOtherInfo() {
var OI = document.getElementById('OtherInfo');
var CheckLists = document.getElementById('cblSelection');
var checkbox = CheckLists.getElementsByTagName("input");
if (checkbox[2].checked) {
document.getElementById('OtherInfo').style.display = "block";
} else {
document.getElementById('OtherInfo').style.display = "none";
}
return true;
}
function onSubmit() {
if (document.getElementById('OtherInfoTextBox').value == "") {
if (checkbox[2].checked) {
alert('Enter other info');
return false;
}
else {
return true;
}
}
else {
return true;
}
}
</script>
and this is your .aspx content
<div>
<label for="labelSelection">Please Select:</label>
<asp:CheckBoxList ID="cblSelection" onclick="ShowOtherInfo(this)" runat="server">
<asp:ListItem Text="AAA" Value="1" />
<asp:ListItem Text="BBB" Value="2" />
<asp:ListItem Text="Other" Value="0" />
</asp:CheckBoxList>
<div id="OtherInfo" style ='display:none'>
<label for="labelOtherInfo">Enter detail if "Other" is selected: </label>
<asp:TextBox ID="OtherInfoTextBox" runat="server" />
</div>
<asp:Button ID="buttonSubmit" runat="server" Text="Submit" CausesValidation="true" OnClientClick="return onSubmit();" />
</div>

How to use validation dynamically?

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>

CustomValidator OnServerValidate Not Working

I am trying to utilize a CustomValidator using the keyword "OnServerValidate"
Here is where I have it setup in my .aspx file:
<div class="label">
<div><label for="parentemail1">Email Address</label></div>
<div><asp:TextBox ID="parentemail1" runat="server" MaxLength="40" Columns="40"></asp:TextBox></div>
<asp:CustomValidator id="ParentEmail1Required"
ControlToValidate="parentemail1"
Display="Dynamic"
ErrorMessage="Required"
ValidateEmptyText="true"
OnServerValidate="ServerValidator"
runat="server"/>
</div>
and here is the C# code behind method for OnServerValidate:
protected void ServerValidator(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}
Am I missing something, shouldn't the CustomValidator fire when the form is submitted?
I've read through a bunch of posts and even tried this with a RequiredFieldValidator on the same control but no luck. I have this working with ClientValidationFunction but I want to access the properties in the code behind instead of the DOM.
Any help would be greatly appreciated.
Try this
protected void ServerValidator(object source, ServerValidateEventArgs args)
{
if(args.IsValid == false)
return;
Response.Redirect("NextPage.aspx");// It will not fire if page is not valid.
}
Well, the argument args is not sent to server and that's why you don't get server message. Add a button can do this.
Change the code to
<div>
<div class="label">
<div><label for="parentemail1">Email Address</label></div>
<div><asp:TextBox ID="parentemail1" runat="server" MaxLength="40" Columns="40"></asp:TextBox>
<br />
<asp:Button ID="btnSendData" runat="server" Text="Send Data" />
</div>
<asp:CustomValidator id="ParentEmail1Required"
ControlToValidate="parentemail1"
Display="Dynamic"
ErrorMessage="Required"
ValidateEmptyText="true"
OnServerValidate="ServerValidator"
runat="server" SetFocusOnError="True"/>
</div>
</div>

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

Categories

Resources