Checkbox Custom Validator with ValidationSummary not working - asp.net

I have the following validation which is working fine for the rest of my fields, but trying to get a custom validator to work as part of the validation summary for a checkbox but no joy.
This is what I have at the moment
<script language="javascript" type="text/javascript">
function ValidateTandCs(source, args)
{
args.IsValid = document.getElementById('<%= optIn.ClientID %>').checked;
}
</script>
<asp:ValidationSummary CssClass="highlight"
id="ValidationSummary1"
HeaderText="<p>Please amend these errors below to continue with your
application.</p>" Runat="server" />
<asp:CheckBox id="optIn" runat="server"></asp:CheckBox> I agree to the terms and
conditions of this site and I wish to Opt In for registration.
<asp:CustomValidator ID="valTandCs" ClientValidationFunction="ValidateTandCs"
ValidationGroup="ValidationSummary1" runat="server"
ErrorMessage="Please accept Terms and Conditions before submitting.">
</asp:CustomValidator>
But when I click submit I only see the error messages for my other fields and nothing for this checkbox...any ideas ?

You had this in your code:
document.getElementById('<%= optIn.ClientID %><%= optIn.ClientID %>').checked;
change it to:
document.getElementById('<%= optIn.ClientID %>').checked;
Also set ControlToValidate property for CustomValidator:
<asp:CustomValidator ID="valTandCs" ClientValidationFunction="ValidateTandCs"
ControlToValidate="optIn" //
ValidationGroup="ValidationSummary1" runat="server"

Related

Asp.net validation error message to change labels text

I am using asp.net validation controls for validating user input. What i want is to change the label text with the error message generated by the validation control.
<asp:Label ID="Label1" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="nameB" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="business" runat="server" ErrorMessage="Please tell us your name." ControlToValidate="nameBuisness" CssClass="errMsg" Display="Dynamic"></asp:RequiredFieldValidator>
Thank you.
One way is to handle the submit-button's OnClientClick-event and call a javascript function like:
<script type="text/javascript">
function displayValidationResult() {
// Do nothing if client validation is not available
if (typeof (Page_Validators) == "undefined") return;
var LblName = document.getElementById('LblName');
var RequiredName = document.getElementById('RequiredName');
ValidatorValidate(RequiredName);
if (!RequiredName.isvalid) {
LblName.innerText = RequiredName.errormessage;
}
}
</script>
<asp:Label ID="LblName" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="TxtNameBusiness" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredName" ValidationGroup="business"
runat="server" ErrorMessage="Please tell us your name." ControlToValidate="TxtNameBusiness"
CssClass="errMsg" Display="None"></asp:RequiredFieldValidator>
<asp:Button ID="BtnSumbit" runat="server" Text="Submit"
OnClientClick="displayValidationResult()" ValidationGroup="business" />
I've used some of the few ASP.NET client validation methods available. I've also renamed your controls to somewhat more meaningful and added a submit-button.
ASP.NET Validation in Depth
If your requirement is that you want to do this validation using the built-in ASP.Net validation controls, then you will need to use the ASP.Net CustomValidator control. This cannot be done using the ASP.Net RequiredFieldValidator control. To do the validation you specified, put a CustomValidator control on on your page so that the markup looks like this:
<asp:Label ID="Label1" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="nameB" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustValidator" runat="server" ControlToValidate="nameB"
ValidateEmptyText="true" ErrorMessage="Please tell us your name."
onservervalidate="CustValidator_ServerValidate" Display="none" >**</asp:CustomValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" CausesValidation="true" />
You then need to write your custom validator. The server-side validation code looks like this:
protected void CustValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrWhiteSpace(args.Value))
{
Label1.Text = CustValidator.ErrorMessage;
args.IsValid = false;
}
else
{
Label1.Text = "Whats your name";
args.IsValid = true;
}
}
This custom validator will give you the behavior you desire.
In general when you use a CustomValidator control, you should do both server-side validation (for security) and client-side validation (for a better UI experience). To get client-side validation, you will need to write a client-side function in javascript and/or jQuery to do similar validation and then assign it to the ClientValidationFunction of the custom validator.
Further information on the CustomValidator control can be found in the MSDN documentation.

how to stop a series of validators in a validationgroup to stop firing upon error? asp.net

there are 3 validators on an textbox,
asp:RegularExpressionValidator
asp:RangeValidator
asp:CompareValidator
some input will trigger all 3 of them, how can I stop firing the rest upon any error?
May be this can help you.. you can intercept ValidatorValidate method of ASP.Net validation framework and selectively disabled the validator controls you want based on any given validation control result.
<asp:TextBox ID="tbText" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator EnableClientScript="true" ValidationExpression="\d" ID="rang" runat="server" ControlToValidate="tbText" >sdfsdfsdfsdfsdfsd</asp:RegularExpressionValidator>
<asp:RangeValidator EnableClientScript="true" Type="Date" MinimumValue="10/10/2000" MaximumValue="10/10/2013" runat="server" ID="rang2" ControlToValidate="tbText" >23444444444444</asp:RangeValidator>
<asp:Button ID="btn" runat="server" Text="submit"/>
<script language="javascript">
var oldValidatorValidate = ValidatorValidate;
function MyValidatorValidate(val, validationGroup, event) {
//first call the original one
oldValidatorValidate(val, validationGroup, event);
//Here you can check val.isvalid - e.g write your logic here, like check for the correct validator etc etc
//alert(val.id + ":" + val.isvalid);
if (!val.isvalid) {
var myVal = document.getElementById('<%=rang2.ClientID %>');
//ValidatorEnable(myVal, false);
}
}
ValidatorValidate = MyValidatorValidate;
</script>

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!

No error message displayed for custom validator

I have a requirement that one of multiple fields is required. Using custom validator the even fires, false is returned, but no error message is display and the form validates.
What am I missing? I have tried with and without ValidationSummary.
Thanks!
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator>
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList" runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" />
protected void validatePhone(object sender, ServerValidateEventArgs e)
{
e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true;
}
You have to set the ControlToValidate to some TextBox.
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnabEnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ControlToValidate="txtHomePhone"/>
Check out this article. Basically you need to wire up the client side validation.
Add the following just before the closing form tag changing the control names as needed:
<%-- This configures the validator to automatically--%>
<%-- update when either of these controls is changed --%>
<script type="text/javascript">
<!--
ValidatorHookupControlID("<%= MyControl1.ClientID %>",
document.getElementById["<%= CustomValidator1.ClientID %>"]);
ValidatorHookupControlID("<%= MyControl2.ClientID %>",
document.getElementById["<%= CustomValidator1.ClientID %>"]);
//-->
</script>
Alternatively use this control
Issue was completely my fault. On my submit button the final thing I do is a Response.Redirect. The message was coming up, but then the Thank you page was being presented. Now only doing the Response.Redirect if the customvalidator returns true.

Enable/disable RequiredValidator on client-side / CustomValidator not firing

I've got a drop-down where the user selects a Country. It is a required "field".
Next to it, there is a textfield named State. If the user selects US, then the field State is required. If the user selects e.g. Sweden, the State is not required, since Sweden has no states.
Example code:
<asp:DropDownList runat="server" ID="Country"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="Country"
runat="server" Display="Static" ErrorMessage="Required field" />
<asp:TextBox runat="server" ID="State"></asp:TextBox>
<asp:CustomValidator ClientValidationFunction="DoesntGetFiredIfStateIsEmpty"
runat="server" Display="Static" ErrorMessage="Required field" />
<!-- SO, RATHER THIS TOGETHER WITH CONDITIONAL FIRING -->
<asp:RequiredFieldValidator ControlToValidate="State"
runat="server" Display="Static" ErrorMessage="Required field" />
My question to you is: How can I make this CustomValidator fire validation when it is empty?
Or put simplier: How can I make a RequiredValidator fire conditionally?
Or simplest: How can I enable/disable a RequiredValidator on client-side?
Try doing this with javascript to enable and disable validators
ValidatorEnable(RequiredFieldValidatorId, false);
Check out this question that I answered.
Asp.net has a client side javascript function to manage the validators, the "ValidatorEnable" function,
ValidatorEnable(RequiredFieldValidatorId, false);
you can call it simply using javascript, you must send the validator object to the function (not only its id).
if (x==y) {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), false);
} else {
ValidatorEnable($('#<%=rfvFamily.ClientID %>'), true);
}
or
if (x==y) {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", false);
} else {
ValidatorEnable(document.getElementById("<%=rfvFamily.ClientID %>", true);
}
full documnet on:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
another way is to Set in your DropDownList CausesValidation="false" to avoid that the validators block a postback when you change the DropDownList entry.
(*) Remember this function is for client side, for disabling validator in server side, you must to disable validator on page postback too.
if (IsPostBack){
if (x==y) {
rfvFamily.Enabled = false;
}
}

Resources