Do not fire custom validate on OnChange event of a textbox - asp.net

I am using a custom validator to validate a textbox content.
Everytime the user leaves this textbox, my client script is called, which is, in my case, a little bit annoying.
I want the validation only to be performed when the user clicks on a button given button (which is already happening).
Is there any way to avoid the validation to be performed on the OnChange event of the TextBox?
My code is here:
function isGroupNameUnique(sender, args) {
var valid = true;
var tokens = $('#hdnGroupNames').val().split(',');
var groupName = $('#<%= txtGroupName.ClientID %>').val();
$.each(tokens, function (i) {
if (groupName == this)
valid = false;
});
args.IsValid = valid;
}
<asp:TextBox ID="txtGroupName" runat="server" />
<asp:Button ID="btnAddGroup" runat="server" Text = "Add" onclick="btnAddGroup_Click" class="bGraySmaller" ValidationGroup="AddGroup"/>
<asp:CustomValidator ID="validatorGroupNameAlreadyExists" runat="server" ControlToValidate="txtGroupName" ErrorMessage="The Group Name has to be unique" ValidationGroup="AddGroup" ClientValidationFunction="isGroupNameUnique" />

Remove the ControlToValidate property on the CustomValidator(what is the only Validator where this property is not mandatory). Set the same ValidationGroup on the TextBox.
<asp:TextBox ID="txtGroupName" ValidationGroup="AddGroup" runat="server" />
<asp:CustomValidator ID="validatorGroupNameAlreadyExists" runat="server" ErrorMessage="The Group Name has to be unique" ValidationGroup="AddGroup" ClientValidationFunction="isGroupNameUnique" />

Related

Validate dropdown list using required field validator not working

I have an asp dropdown and I am trying to validate it but the validating is just not working.
My dropdown and validator:
<asp:DropDownList CssClass="form-control"
runat="server" ID="cmb_Addresses"
ValidationGroup="ShippingAddress">
</asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="cmb_Addresses"
ValidationGroup="ShippingAddress"
InitialValue="0"
Display="dynamic"
ErrorMessage='Please select an address'
runat="server"/>
And here is the method that populates the dropdown:
private void SetupAddresses()
{
var accountService = new AccountService();
var userService = new UserService();
var username = userService.GetLoggedInUser();
var addresses = accountService.GetAddressesForUser(username);
cmb_Addresses.Items.Clear();
cmb_Addresses.Items.Add(new System.Web.UI.WebControls.ListItem("--Please Select--", "0"));
foreach (var address in addresses)
{
cmb_Addresses.Items.Add(new System.Web.UI.WebControls.ListItem(address.Name, GetAddressValue(address)));
}
}
I have tried all the suggestions I have found on the net but they not working.
Oh, the method is called in a !IsPostback
Did you add the correct ValidationGroup to the button that does the PostBack? Because I tested your snippet and it works.
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ShippingAddress" />
If you did add it to the button, there is probably a javascript error somewhere on the page that is interfering with the Validator. If there are errors the Validator won't work and the form is posted.

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>

Check if value of textbox extended with MaskedEditExtender is valid?

Below is my code:
<asp:TextBox
ID="FromDateTextBox"
runat="server" />
<asp:ImageButton
ID="FromDateImageButton"
runat="server"
ImageUrl="~/images/calander.png" />
<ajaxkit:CalendarExtender
ID="FromDate"
runat="server"
TargetControlID="FromDateTextBox"
CssClass="CalanderControl"
PopupButtonID="FromDateImageButton"
Enabled="True" />
<ajaxkit:MaskedEditExtender
id="FromDateMaskedEditExtender"
runat="server"
targetcontrolid="FromDateTextBox"
Mask="99/99/9999"
messagevalidatortip="true"
onfocuscssclass="MaskedEditFocus"
oninvalidcssclass="MaskedEditError"
masktype="Date"
displaymoney="Left"
acceptnegative="Left"
errortooltipenabled="True" />
<ajaxkit:MaskedEditValidator
id="FromDateMaskedEditValidator"
runat="server"
controlextender="FromDateMaskedEditExtender"
controltovalidate="FromDateTextBox"
emptyvaluemessage="Date is required"
invalidvaluemessage="Date is invalid"
display="Dynamic"
tooltipmessage="Input a date"
emptyvalueblurredtext="*"
invalidvalueblurredmessage="*"
validationgroup="MKE" />
I've set Culture="auto" UICulture="auto" in #Page directive and EnableScriptGlobalization="true" EnableScriptLocalization="true" in script manager to have client culture specific date format in my textbox.
I also have a Go button on my page on which I will do a partial post back. So, I want to validate the FromDateTextBox in javascript when the Go button is clicked.
UPDATE
I know how to create a javascript click handler. But because masked editor is already validating the date on focus shift, I'm thinking there should be some boolean property (like IsValid) exposed by it which will allow me to see if the text box contains valid date.
FURTHER TRIALS
I also tried below code and Page_Validators[f].isvalid always returns true even when the date is invalid and MaskEditValidator shows me a red star near the Text box.
function isDateValid() {
var b = true;
for (var f = 0; f < Page_Validators.length; f++) {
if (!Page_Validators[f].isvalid)
b = false;
}
return b;
}
$('#GoButton').click(function() {
if (!isDateValid()) {
return false;
}
loadProducts();
});
Sorry do you mean that your MaskedEditValidator is not working when clicking GO button? Or if you want to write some js to check the date yourself? In this case you can add a client onclick event to GO button. One example in code behind is:
goButton.Attributes["onclick"] = "if (!CheckDate()) return false;";
And in the page file add a javascript function:
function CheckDate()
{
//check the date here
return isValid;
}
Now if the date is not valid,the CheckDate() will return false, the goButton event will also return without posting back.
I resolved it. Basically when there is an invalid date entered in the textbox the MaskedEditExtender changes the provided (OnInvalidCssClass="MaskedEditError") class of the textbox and I picked it up as a checking point for validation.
$('#GoButton').click(function () {
if($('#<%=FromDateTextBox.ClientID%>').hasClass('MaskedEditError')) {
return false;
}
}

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;
}
}

Client Side javascript call from ASP control doesn't reset visibility

I have a javascript to enable text boxes when called, I want to trigger this code when a user picks value "Custom" from a dropdownlist, so that I can display/Hide these new textboxes.
function setVisibility(DropDownListID) {
var element = document.getElementById(DropDownListID);
var element1 = document.getElementById("TestBox1");
if (element.value == "Custom") {
element1.visible = !element1.visible ;
}
<asp:DropDownList ID="DateRangeDropDownList" runat="server" Enabled="True" onChange="setVisibility('DateRangeDropDownList');">
<asp:ListItem>Some Value</asp:ListItem>
<asp:ListItem>Custom</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TestBox1" runat="server"></asp:TextBox>
For some reason it doesn't seem to work. Any ideas?
Because ASP.NET render's your control's is different than you specify in your function call. Use control's ClientID property to get rendered id attribute for a server side control. Here I put dropdown itself as a parameter, and access to your textbox by it's ClientID :
function setVisibility(yourDropdown) {
var element1 = document.getElementById(<%= TestBox1.ClientID %>);
if (yourDropdown.value == "Custom") {
element1.visible = !element1.visible ;
}
<asp:DropDownList ID="DateRangeDropDownList" runat="server" Enabled="True"
onChange="setVisibility(this);">
<asp:ListItem>Some Value</asp:ListItem>
<asp:ListItem>Custom</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TestBox1" runat="server"></asp:TextBox>

Resources