How to use client side scripts with customValidators? - asp.net

If I leave the checkbox blank and click the submit button, nothing happens. If I check it and hit the submit button, nothing happens.
The javascript fires, I just don't know why no text is displayed and the page doesn't postback.
function ValidateCheckBox(source, args) {
args.IsValid = document.getElementById('<%= cb_confirmation.ClientID%>');
}
Here is the validator:
<asp:CustomValidator runat="server" ID="cb_Validator"
OnServerValidate="CheckBoxRequired_ServerValidate"
CssClass="errorMessage" Display="Static" ErrorMessage="You must select this box to confirm"
Text="***" ClientValidationFunction="ValidateCheckBox">
</asp:CustomValidator>
The checkbox:
<asp:CheckBox ID="cb_confirmation" runat="server" />
And the button that causes validation is
<asp:Button ID="btn_submit" runat="server" Text="Submit" CausesValidation="true"
CssClass="submitButton" onclick="btn_submit_Click"/>
EDIT: The solution was to add a ".checked" to the end of the javascript function.

Related

Why is this CustomValidator client function not firing?

I have a dropdown with the Id of "BACKGROUND" and if nothing is selected or the value is other, it should fire my client side validation function, but it is not. Am I missing something?
I have the following client side function:
function cv26(oSrc, args) {//BACKGROUND,BG_OTHER
alert("cv26");
var otherCtrl = document.getElementById("BG_OTHER");
args.IsValid = (args.Value != " ") || (otherCtrl.value.length > 0);
}
My Custom validator looks like this:
<asp:CustomValidator ID="cv26" runat="server" ErrorMessage="26. Background is required." ControlToValidate="BACKGROUND" ClientValidationFunction="cv26" Display="Dynamic" ValidateEmptyText="true">*</asp:CustomValidator>
The problem is the value in ClientValidationFunction. It should be ClientValidationFunction="cv26" as it cannot find val_cv26
Change this:
<asp:CustomValidator ID="cv26" runat="server"
ErrorMessage="26.
Background is required."
ControlToValidate="BACKGROUND"
ClientValidationFunction="val_cv26"
Display="Dynamic"
ValidateEmptyText="true">*</asp:CustomValidator>
To:
<asp:CustomValidator ID="cv26" runat="server"
ErrorMessage="26.
Background is required."
ControlToValidate="BACKGROUND"
ClientValidationFunction="cv26"
Display="Dynamic"
ValidateEmptyText="true">*</asp:CustomValidator>
Or rename your JavaScript function to val_cv26.
Problem #1: Function names DO NOT MATCH
ClientValidationFunction does not match the function name.
In your javascript you declare function cv26, but in your CustomValidator you have val_cv26 for ClientValidationFunction. So you either change your javascript function to val_cv26 or change the ClientValidationFunction to cv26
Problem #2: Validation Groups
In your original code you did not specify any validation groups. Notice that both the CustomValidator and Button2 have ValidationGroup="hi". They must belong to the same validation group. You need validation groups if you have multiple buttons for example and you only want one of the buttons to validate user input. If you only have ONE button then this is not a problem.
ASPX:
<asp:DropDownList ID="BACKGROUND" runat="server">
<asp:ListItem Text=" --- SELECT ---" Value=""></asp:ListItem>
<asp:ListItem Text="A"></asp:ListItem>
<asp:ListItem Text="B"></asp:ListItem>
<asp:ListItem Text="C"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="cv26" runat="server"
ErrorMessage="26. Background is required."
ControlToValidate="BACKGROUND"
ClientValidationFunction="cv26"
Display="Dynamic" ValidateEmptyText="true"
ValidationGroup="hi">*</asp:CustomValidator>
<asp:Button ID="Button1" runat="server"
Text="Submit" onclick="Button1_Click"
ValidationGroup="hi" />
JavaScript:
function cv26(oSrc, args) {
args.IsValid = (args.Value != "");
}
When is your validation expected to fire?
Please provide the declaration for BACKGROUND
Please provide the declaration for BG_Other
Are BACKGROUND and BG_OTHER on the same ASPX page?

input button causes RequiredFieldValidator to fire

I have an input button on my page that is dynamically created, every time I press it, it fires the RequiredFieldValidator for the blank field in the email address.
is there a way to ovverride it?
input code:
<input class=\"hledat\" id=\"searchbutton\" type=\"image\" src=\"search-button.gif\" value=\"{0}\" onclick=\"search('{1}');\" onkeypress=\"search('{1}');\"/>"
validator code:
<asp:TextBox runat="server" ID="txtEmail" ClientIDMode="Static" Width="98%" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" ErrorMessage="email"
Display="dynamic" ValidationGroup="newsletter" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtEmail" ErrorMessage="email"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="dynamic"
ValidationGroup="newsletter" />
I have an input button on my page that is dynamically created, every
time I press it, it fires the RequiredFieldValidator for the blank
field in the email address. is there a way to ovverride it?
HtmlButton.CausesValidation Property
Mark UP
<button causesvalidation="false" /><button ID="StateQueryButton"
CausesValidation="False"
runat="server">
Submit
</button>
yes, i want it to do a postback
HtmlButton.OnServerClick Method
Code Behind
protected void FancyBtn_Click(object sender, EventArgs e)
{
}
Mark Up
<button causesvalidation="false" /><button ID="StateQueryButton"
CausesValidation="False"
OnServerClick=" FancyBtn_Click"
runat="server" >
Submit
</button>
Make it server side button by writing runat="Server" attribute and make a CausesValidation="true|false" on your requirements. If you do false it will not validate. Do let me know if it solves the problem
try to add runat="server" to input button as shown:
*Note* the runat="server". While asp:button probably renders similarly, if what you really want it an HTML button input, you can use that. Yes, ASP.NET will pick up the value on the server side.**
<input type="button" runat="server" id="btnTest" value="change" onclick="doPostBack('btnTest', '');"/>

asp.net required field validation called on every button action

I wrote a simple asp.net code with the asp.net required validator control, the problem is that I only have one submit button called GO, and a dropdownlist that looks for the selection :
clear, submit, cancel.
No matter what option is selected, the required field validation is being fired.
Is there a way to code the page so only when the selected value is Submit it validates?
<asp:TextBox runat="server" id="txtName" />
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />
<br /><br />
<asp:DropDownList ID="dpAction" runat="server">
<asp:ListItem>Submit</asp:ListItem>
<asp:ListItem Value="Reset">Reset</asp:ListItem>
<asp:ListItem>Cancel</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnAction" runat="server" onclick="btnAction_Click" Text="Go"
Width="40px" />
You will probably have to use a custom validator, and you would need to write the client side code for it also if you want client side validation.
I'm assuming you have a text box or something else that is required when "dpAction" is set to "Submit"?
So for example you would do something like this in your markup
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="TextValidate"
ControlToValidate="TextBox1"
ErrorMessage="Text must be specified if Submit is selected">
and in your code-behind
protected void TextValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = dpAction.SelectedValue == "Submit" && !String.IsNullOrEmpty(textbox1.Text);
}
using "required" attribute.
its new in html 5
you should set ValidationGroup for each Validator!
for all controls that you want to be validated and the button to fire the validation:
and the button must have same validaton group with your validator!

AutoPostBack on CheckBox control sometimes fails

If have the below markup.
<asp:checkbox id="chkTVLic" runat="server" text="TV Licence" oncheckedchanged="chkDocs_CheckChanged"
autopostback="true" CausesValidation="false" />
<asp:panel id="pnlTVLic" runat="server" visible="false">
<div class="toggle-item-link1 document-date">
<asp:panel id="pnlTVLicIssueDate" runat="server">
<p>
Please enter the date of issue
</p>
<div class="fm-req">
<asp:textbox id="txtTVLicIssueDate" cssclass="tb size2" runat="server" onblur="return true;"></asp:textbox>
<cc2:calendarextender id="caleTVLicIssueDate" runat="server" targetcontrolid="txtTVLicIssueDate"
popupbuttonid="ibnTVLicIssueDate" popupposition="BottomLeft" animated="true"
format="dd/MM/yyyy">
</cc2:calendarextender>
<asp:imagebutton id="ibnTVLicIssueDate" runat="server" imageurl="../images/img-calendar-day.png"
alternatetext="Calendar" tooltip="Pick Date" cssclass="date-picker" />
<asp:requiredfieldvalidator id="rfvTVLicIssueDate" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
display="Dynamic" errormessage="Required" setfocusonerror="true" validationgroup="TVLic"></asp:requiredfieldvalidator>
<asp:comparevalidator id="cmvTVLicIssueDate" CssClass="error" runat="server" errormessage="Not a valid date"
controltovalidate="txtTVLicIssueDate" operator="DataTypeCheck" type="Date" setfocusonerror="true"
validationgroup="TVLic" display="Dynamic" cultureinvariantvalues="true"></asp:comparevalidator>
<asp:customvalidator id="cuvTVLicIssueDate12Months" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
validationgroup="TVLic" display="Dynamic" onservervalidate="cuvDocIssueDate12Months_ServerValidate"
errormessage="Document must be less than 12 months old."></asp:customvalidator>
</div>
</asp:panel>
<asp:panel id="pnlTVLicApprove" runat="server">
<asp:LinkButton id="lbnTVLicApprove" runat="server" CssClass="screen-hide"
alternatetext="Confirm TV Licence" tooltip="Confirm TV Licence" Text="OK" CausesValidation="false" OnClick="lbnApproveConfirm_Click" />
<asp:imagebutton id="ibnTVLicApprove" runat="server" imageurl="../images/img-accept-doc-off.png"
alternatetext="Approve" tooltip="Approve" cssclass="approval-btn" causesvalidation="true" validationgroup="TVLic" OnMouseDown="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" OnClientClick="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" />
<span class="approval-label">Accept document:</span></asp:panel>
</div>
</asp:panel>
The app is written in c# but i havn't posted any actual code as all the user code related to this markup seems to work fine.
The problem is the CheckBox chkTVLic has causes validation set to false and autopostback set to true. So whatever happens when i check and uncheck the checkbox it should postback. Most of the time this is exactly what it does and the result is to show and hide pnlTVLic when it is checked and unchecked. However if any on the validators within the panel fire, the checkbox does not cause a postback the first time. It will on all subsequent times but never the first. However it should ALWAYS cause a postback. What could be stopping it. Before someone asks there is no use written client side code, everything is pure .net markup and c# code.
I don't see why it shouldn't postback when you check/uncheck the checkbox, but if the only purpose of that checkbox is to hide/unhide a panel, I would rather do it in javascript. Doing a full postback to the server just for hiding some panel seems really bad.
In javascript you can do this to hide the panel:
document.getElementById('<%=pnlTVLic.ClientID%>').display='none';
And this to show it:
document.getElementById('<%=pnlTVLic.ClientID%>').display='block';
It's going to be so much faster and better. Just put a regular checkbox instead of the ASP.NET one and subscribe to the onclick event.
Sorry, one more comment:
I think you are wrong when you say that the checkbox should ALWAYS cause a postback. No, if one of the validators fires inside the panel, the checkbox will not cause a postback until the condition is satisfied.
This is what I did and it worked.
on checkbox onclick event I disabled all the validation controls and immediately did Page_ClientValidate(); and it worked.

Required field validator not working

I have used a required field validator followed by a regular expression validator but the required field validator is not working.....
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000"
ValidationGroup="Valtxt" TabIndex="2" Rows="4">
</asp:TextBox>
<asp:RegularExpressionValidator ID="regValSummary" runat="server"
ControlToValidate="txtSummary" Display="Dynamic"
ValidationExpression="[^<>&#!]*" ValidationGroup="Valtxt">
Invalid characters(<>&#!) are not allowed
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqvalSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Summary is required"
ValidationGroup="Valtxt" Display="Dynamic">
</asp:RequiredFieldValidator>
can anyone sees the problem???
The RequiredFieldValidator is triggered by the client side onchange event. It sounds like you're expecting it to be triggered by the onblur event, such that tabbing away from the textbox would fire the validation.
Before jumping to that, I suspect this is what you are seeing and to validate that it's actually working you need to trigger onchange. To do so, enter some text in the textbox, tab away, tab back to it, clear the textbox, then tab away once more. You should now see the RequiredFieldValidator's error message since it's contents have changed.
Back to the onblur issue. To accomplish that behavior you could add the onblur attribute in your code-behind and have it call the ValidatorValidate(...) JavaScript method as follows:
void Page_Load(object sender, EventArgs e)
{
txtSummary.Attributes.Add("onblur", "ValidatorValidate(" + reqvalSummary.ClientID + ")");
}
Alternately, you could accomplish the same thing in markup. First, add this script block:
<script type="text/javascript">
function rfvBlur() {
var rfv = document.getElementById("<%= reqvalSummary.ClientID %>");
ValidatorValidate(rfv);
}
</script>
Second, update the <asp:TextBox.../> markup by adding onblur="rfvBlur()" so that it now looks like this:
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px" CausesValidation="true"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000" ValidationGroup="Valtxt"
TabIndex="2" Rows="4" onblur="rfvBlur()" />
Yet another option is to validate the entire ValidationGroup by adding the following attribute to your <asp:TextBox.../> markup (no additional script block needed):
onblur="Page_ClientValidate('Valtxt')"
Adding this line to <appSettings> section of web.config worked for me (I had a problem when all validators stopped working when project was upgraded to .NET 4.5):
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Source:
http://forums.asp.net/t/1876231.aspx?ASP+Net+4+5+Validation+Controls+not+working+with+AJAX+ToolkitScriptManager1
Why don't you change the regular expression of the "RegEx" validator to check if the textbox is empty instead of use another validator?
Anyway probabily you have not specify ValidationGroup="Valtxt" for the button or the control that raise the postback. Just add ValidationGroup="Valtxt" to the button or the server control that raise the post to the page
I put the following at the top of my btn_Click event handler (to prevent further code execution) and upon 'return', the rfv messages show...
Page.Validate("your validation group");
if (!Page.IsValid)
{
return;
}
<asp:TextBox ID="txtSummary" runat="server" TextMode="MultiLine" Width="700px"
CssClass="txtStyle" Font-Names="Arial" MaxLength="1000"
TabIndex="2" Rows="4">
</asp:TextBox>
<asp:RegularExpressionValidator ID="regValSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Invalid characters(<>&#!) are not allowed" Text="*"
ValidationExpression="[^<>&#!]*" ValidationGroup="Valtxt">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="reqvalSummary" runat="server"
ControlToValidate="txtSummary" ErrorMessage="Summary is required" Text="*"
ValidationGroup="Valtxt">
</asp:RequiredFieldValidator>

Resources