How to use validation dynamically? - c#

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>

Related

Can't apply CssClass via C#

I am trying to apply CssClass when validator is false, it worked for me in the past and now I don't know why it doesn't work.
Textbox:
<asp:TextBox ID="txtPass"
AutoPostBack="false"
ClientIDMode="Static"
runat="server"
placeholder="Password (8 - 16 digits)"
CssClass="Text"
type="password"
ValidationGroup="check">
</asp:TextBox>
Validators attached to this textbox:
<asp:RegularExpressionValidator ID="revPass"
runat="server"
Display="None"
ControlToValidate="txtPass"
EnableClientScript="false"
ValidationExpression="[a-zA-Z0-9]{8,16}"
ValidationGroup="check">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="rfvPass"
runat="server"
EnableClientScript="false"
ControlToValidate="txtPass"
Display="None"
ValidationGroup="check">
</asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvPasswords"
runat="server"
ErrorMessage="Passwords do not match!"
EnableClientScript="false"
CssClass="error"
ControlToCompare="txtPass"
ControlToValidate="txtConPass"
ValidationGroup="check">
</asp:CompareValidator>
But I have to say that only the last one works. The validators work, just not changing CssClass.
EDIT:
It is not even enteres the if statemant I checked it. there is the if statement:
if (!(revPass.IsValid) || !rfvPass.IsValid)
{
txtPass.CssClass = "txtError";
}
If you want to Apply Css on your Validator's Error messages Then you have to set CssClass Attribute of all Validators..
UPDATE :Sorry about that, i misunderstood your Question. Did you try this On Code behind
protected void Button1_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
// code executed when validation are valid
}
else
{
txtPass.CssClass = "Your New Class";
txtConPass.CssClass = "Your New Class";
}
}

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>

enabling/disabling validation from code behind c#

I have some asp code written for a form. One of the fields must have 3 types of validation, 2 of which are alway enabled, the other 2 must be "enabled" only if a peculiar value has been selected from a dropdownlist.
How am I supposed to achieve this task?
I have disabled the 2 extra validations by defaults and wold like to reactivate on dropdownlist specific selection.
I show you my code here.
ASP.NET code:
<tr>
<td class="style1">
<asp:Label ID="LabelPiva" runat="server" Text="Partita IVA" meta:resourcekey="LabelPiva" Font-Bold="True" />
</td>
<td>
<asp:TextBox ID="pivaTextBox" runat="server" Text='<%# Bind("piva") %>'
MaxLength="50" Width="400px" />
<asp:RequiredFieldValidator ID="RequiredPiva" runat="server"
ControlToValidate="pivaTextBox"
ErrorMessage="<%$ Resources:Resource, CampoObbligatorio %>" Display="Dynamic"
CssClass="little_text" />
<asp:CustomValidator ID="PivaEsistente" runat="server"
ErrorMessage="Partita IVA esistente nel database" meta:resourcekey="PivaEsistente"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
onservervalidate="PIVAEsistente_ServerValidate"></asp:CustomValidator>
<asp:RegularExpressionValidator ID="PivaSize" runat="server"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
ErrorMessage="Controllare la lunghezza della partita iva. 11 caratteri e solo numeri."
ValidationExpression="^[0-9]{11}$" Enabled="False" ValidationGroup="soloItalia">
</asp:RegularExpressionValidator>
<asp:CustomValidator ID="PivaErrata" runat="server"
ErrorMessage="Partita IVA non corretta. Controllare le cifre." meta:resourcekey="PivaErrata"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
onservervalidate="ValidatePI" Enabled="False" ValidationGroup="soloItalia"></asp:CustomValidator>
</td>
</tr>
The CustomValidator with id PivaErrata and the RegularExpressionValidator with id PivaSize must be fired only when dropdownlist hits the "it" value.
This is the code-behind in c# to intercept the value of the dropdownlist:
protected void nazioneDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
DropDownList ddlProv = (DropDownList)FormUser.FindControl("provinciaDropDownList");
if ("it".Equals(ddl.SelectedValue))
{
ddlProv.Enabled = true;
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}
}
As you can see, another dropdownlist gets enabled when that specific value "it" is fired in the nations dropdownlist.
I would like to activate the validations controls too.
I assigned a validationgroup to those 2 validations, but I am not sure how to "enable" them at once.
Any help?
Thank you very much.
you can use Enabled property of the Validation controls to enable or disable them.
Try This:
if (ddl.SelectedItem.ToString().Equals("it"))
{
ddlProv.Enabled = true;
//add these two statements to enable
PivaSize.Enabled=true;
PivaErrata.Enabled=true;
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
//add these two statements to disable
PivaSize.Enabled=false;
PivaErrata.Enabled=false;
}

How to pass control.ClientId to an OnClick function in ASP.NET?

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>

Validation with one radio button option only

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.

Categories

Resources