Validate AJAX Toolkit Combobox Regular Expression Validator - asp.net

I was wondering if it was possible to validate the ajax toolkit combobox with a regular expression validator. I allow the user to enter values, but only want certain values ( regex [0-9]{0,1}[0-9]{1}|-7|-8|-9) to be allowed. I could use the custom validator, but I would need to also create javascript function to validate on the client side. If there is a better way I would love to hear it. Thanks. Here is the combobox code:
<asp:ComboBox CssClass="required" DropDownStyle="Simple"
ID="DaysDeployed" Width="50" runat="server">
<asp:ListItem Selected="True" Text="" Value="" />
<asp:ListItem Text="Refused" Value="-7" />
<asp:ListItem Text="Don't Know" Value="-8" />
<asp:ListItem Text="Missing Data" Value="-9" />
</asp:ComboBox>

Summary: Instead of using an asp.net button that would normally trigger your postback, make one using html. Have the html button run a javascript function that first checks the regex validation, then (if valid) runs the postback function.
First, I would remove the asp.net button that you use to trigger the server-side code, and replace it with a client-side button. You can follow the steps in another answer of mine if you need help creating this button. Here is the link:
https://stackoverflow.com/questions/14062993/input-type-image-onclick-will-trigger-its-event-but-not-act-well-on-funct/14063911#14063911-Stack Overflow
Second, the javascript function should first validate the data using a regex function. Use something like this:
function validateCombobox(myComboboxValue) {
if(myComboboxValue.match(regularExpressionString)===null){
return false
} else {
return true
};
};
***Note: Regex is a weak area for me so you may need to revise this script a little.
Third, if the input is validated using the script above, then call the postback using javascript. To do this, follow these steps:
Create an on the asp page. This is necessary
because without it, the site will not generate event handlers for
the needed buttonclick event.
Set the link-button's css display property to 'none'. Beware that
link-button's "Visible" attribute my be set to true (this is because
asp.net does not even render the code for controls with a false
visible attribute). To illustrate, if your link-button's cssClass
name is myButton, add this to your css file:
.myButton
{
display: none;
}
Now that the button is created and properly hidden, you can add the
postback function to your javascript function. The postback function
has two parameters, the first is the client side ID of the
link-button control that we created. Beware that the client-side
IDs of asp.net controls are not the same as the ID you assign it
during development. Because of this, we use <%=Control.ClientId %>
to get the control's client ID. If your link-button ID is
"myLinkButton", the following should be your postback function:
__doPostBack('<%=myLinkButton.clientid %>','')
Please note that there are two underscore characters in the
beginning of this function.
Here is an example of the regex validation function and the javascript function that should be called by your new button:
function validateCombobox(myComboboxValue) {
if(myComboboxValue.match(regularExpressionString)===null){
return false
} else {
return true
};
};
function comboBoxButton_click(){
var myComboboxValue = $('#<%=myComboBox.clientid %>').val();
if(validateCombobox(myComboboxValue)==true){
__doPostBack('<%=myLinkButton.clientid %>','');
};
};
I have a lot of distractions at the moment and am a little scatter-brained, so forgive me if these instructions are a little confusing. If you need more assistance, feel free to comment and I'll check back soon.

Related

Why does CustomValidator fire on textbox's onblur

I am building a CustomValidator to handle my own application's logic on time fields ("09:00", "15:35", ...) but I am stumbling on a behaviour that I haven't found any explanation for online.
My focus right now is the validation logic that gets executed client-side.
The problem is, as said in the title, that, if and only if I set the ControlToValidate property in the Validator with the ID of the textbox I am validating, the validation gets fired as soon as focus leaves the textbox; it even fires before the onblur event, which is absolutely detrimental for me, since I am using the onblur event to standardize the time formats (eg "9:00" -> "09:00", "11.45" -> "11:45") and thus, the validation logic potentially receives an incorrect value. If, on the other hand, the ControlToValidate property remains blank, the ClientValidationFunction is fired only on a submit/postback.
The only related answer I've found is this https://stackoverflow.com/a/8649697/450684, but still, to me it makes no sense at all. Why should the presence of a ControlToValidate indicate that I want client-side validation to execute before onblur? I don't want it! Is there any way to supress this behaviour?
Here is an example page:
<asp:TextBox runat="server" AutoPostBack="false" ID="txtBox1" onblur="FormatText(this);" />
<asp:CustomValidator runat="server" ID="CV1" ControlToValidate="txtBox1" ClientValidationFunction="Test1" />
<asp:CustomValidator runat="server" ID="CV2" ClientValidationFunction="Test2" />
<asp:Button ID="btn1" Text="postback" runat="server" OnClick="btn1_Click" />
<asp:Label ID="lbl1" runat="server" />
<script type="text/javascript">
function FormatText(txtBox1)
{
alert('FormatText');
}
function Test1(val, args)
{
alert('Test1');
}
function Test2(val, args)
{
alert('Test2');
}</script>
What I want is both Test1 and Test2 to execute only on btn1's click; instead on txtBox1's onblur event I get Test1 and FormatText executing in this order
ASP.NET's client validation was really fun for me to write and study, don't let this ruin everything :-)
Thx
PS: .NET framework's version is 4.0. Plus, the server-side language is C#, if it matters
I think what is going on is this:
The standard behavior for ASP.NET client-side validation is to validate when the field is exited. That's an observation, not a reference to a published standard (although there may be one.) The out-of-the-box validators all behave this way. All of them require specifying a particular field to validate.
The custom validator allows you to validate a single control (by specifying it with ControlToValidate), or lets you validate a combination of controls, in which case you set ControlToValidate to an empty string. Unless things have changed, you do have to specify it; if you omit the attribute, no validation will occur.
So ... if you specify a control to validate, the custom validator behaves like every other validator and reacts to the user exiting the field. If you don't specify a control to validate, it doesn't know what controls you're interested in, and doesn't do that.
You may be able to work around this by writing a truly custom validator: inherit from BaseValidator. That can actually be a lot of fun.
How to manage events of validation for your control.
You can remove ControlToValidate property from your validator and bind validation for your textbox on textbox event as you wish. You can add some function logic before or after validation also. On button click event validation stay the same without change.
function BindValidation(){$('#txtBox1').on('blur keyup change',function(){ValidatorValidate($('#CV1').get(0));});}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(BindValidation);
//validation function example for CV1 validator
function Test1(val, args)
{
args.IsValid=$('#txtBox1').val().length>0&&$('#txtBox1').val().match(/^\s+$/g)==null;
}

I want iif conditiomn in my radio button

I want to put if condition in my radio button.
I have wrote this code but it does not give me result as I want. you will get idea from my code what actual I need to do. I have loaded user control two time in a single page so I want to call Java Script in page according to control.
<asp:RadioButton runat="server" GroupName="Pricing" class="2deditable iscreatedbydealer isinprivatelabel" onClick='<%this.ID=="ucPricing_Details_Sale"? "setSalePopupRetailPrice();":"setClearancePopupRetailPrice();"%>'
ID="rbManual" />
I think you can dynamic add the onclick event for the control in page load event of server side.
e.g
if("ucPricing_Details_Sale".Equals(this.ID))
{
this.rbManual.Attributes.Add("onclick", "setSalePopupRetailPrice();");
}
else
{
this.rbManual.Attributes.Add("onclick", "setClearancePopupRetailPrice();");
}
The on OnClick event will run on server side. Try using the OnClientClick event instead.
Edit: Deleted my last statement. Mistook me about the context of the call.
Also added code sample:
<asp:RadioButton runat="server"
OnClientClick='<%this.ID=="ucPricing_Details_Sale"?[...]"%>'
ID="rbManual" />

how to check a particular asp.net validation control is valid?

In a web form there are different asp.net validation controls. Is it possible to check a particular validation control is valid ? For example on leaving focus of textbox, first I will check requiredFieldValidatorUserName is valid ? If it is valid then I will check on server using ajax that this user name is not booked already.
Edit:
Explaination: I want to check validity (that input was valid) of a validation control on client side.
Please guide.
All validator controls implement IValidator which contains the IsValid property.
myValidatorControl.IsValid
The best way would be to use a CustomValidator with client side code, as this will display all the error messages, block form submission and also ensure that the validation is repeated at the server side - remember, just because you have client-side validation available, doesn't mean the user's seen it: Always validate your input at the server as well.
Your CustomValidator would then be coded to call the Ajax methods, and would show the error messages correctly to the client:
<asp:Label ID="UserNameLabel" AssociatedControlID="UserName" runat="server">
UserName *:</asp:Label>
<asp:TextBox ID="UserName" runat="server" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
ControlToValidate="UserName" EnableClientScript="true"
ErrorMessage="You must supply a username!" />
<asp:CustomValidator ID="UserNameCustom" runat="server"
ControlToValidate="UserName"
ClientValidationFunction="CheckExisting"
OnServerValidate="UserNameCustomValidate"
ErrorMessage="Username already taken" />
And your ClientValidationFunction should look something like:
<script type="text/javascript">
function CheckExisting(source, arguments) {
// Pass the arguments.Value to your AJAX call:
if (ajaxCallUserNameTaken(arguments.Value)) {
arguments.IsValid = false;
}
}
</script>
(Obviously, you'll need to write the ajaxCallUserNameTaken method to call your page method/web service/etc.)
Doing it this way will ensure that the validation methods happen as expected; this will get called whenever the user tabs out of the textbox leaving a value (it won't get called if the textbox is empty), and will ensure that the user can't submit the page until they supply a unique value. You'll also want to create the method referenced in OnServerValidate to ensure that the value's good once it hits the server too - this should call the same code that the AJAX endpoint uses to reduce duplication of code, etc.
I was originally going to suggest that you could use the Page_Validators object on the client-side to do some checking in the onBlur event, but I don't really think this is suitable here as it results in more pain:
It assumes that although there might be more than one validator on the page, there's only the RequiredFieldValidator on the control we're checking
The RequiredFieldValidator isn't fired during OnBlur if a user moves out of a control without setting a value - only if they set and clear the value, so even if isvalid is true, you need to check for an empty string!
You could do this by setting the ValidationGroup for the Validator control that you want to treat as separate from the others. Make sure it matches the ValidationGroup of the control it's validating (your username field).
I have just faced the same issue and I Set CausesValidation="true" to the textbox control and it worked. Just give it a try :)
I have been messing around with this around for a bit and found a rather easy (not so efficient) solution to handle this using jQuery.
Use this function to check the validity of your control:
function validateControl() {
return $('#YOUR_VALIDATOR_ID').css("visibility") == "visible"
if you're using Display="Dynamic" on your validator then the function is like so:
function validateControl() {
return return $('#YOUR_VALIDATOR_ID').css("display") == "inline"
Be sure to check the true ID of your validator if you're using a Masterpage, as it will be different than the one in your IDE. Do so by viewing the page source in your browser.
The best solution will be of course to validate your form in some other way, using JavaScript or a CustomValidator that lets you write your own code.

asp.net button use javascript return function

I have an asp:button control and am using the "CommandName" and "CommandArgument" parameters in the .aspx file. The CommandName is found with <%# Eval("Name") %>, but the CommandArgument has to be found via a javascript function. However, I'm not quite sure how to do this inline. The function returns a number (integer), which is to be used as the value of the CommandArgument. Is it possible to do this?
Thanks
EDITED TO ADD CODE
I've added an example code (don't have access to the real code atm). However, basically, the CommandArgument should be the value returned by the function CalculateLength().
function CalculateLength(a,b) {
return a*b;
}
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName=<%# Eval("Name") %> CommandArgument= ??? //Should be result of CalculateLength(a,b).
I am not sure how you are going to get the javascript to work because the aspx code is running server side and building the output for your button. By the time the javascript runs the page code has already been built and the button's html and attached javascript as well.
Is there anyway to calculate the function server side and then just do:
CommandArgument="<%= CalculateLengthServerSide() %>"
You don't need to just use the data your binding to, you can call any server side function.
Edit: Try switching your label that stores the quantity to a textbox and making it read only so uses will not mess with it. After the button is clicked, you should be able to find the textbox control and read out the posted value.

Client-Side validation with groups

I have several tabs that are loaded via ajax, and each one has a set of validators. I want to allow the user to change tabs only if the tab is valid
I thought setting a validationgroup to the validators and then check for the specific group like this, would work:
function validatePage(group) {
return Page_ClientValidate(group);
}
However, when I call the function, it always returns true. Can anyone see what I'm doing wrong?
I check it like this
alert(validatePage("presentaciones"));
And I have some validators:
// (...)
<asp:TextBox ValidationGroup="presentaciones" id="txtDescription" runat="server" Text='<%# Eval("Description") %>' MaxLength="50" />
<asp:RequiredFieldValidator ID="DescriptionRequiredFieldValidator" runat="server" ControlToValidate="txtDescription" SetFocusOnError="true" ValidationGroup="presentaciones" ErrorMessage="Debe ingresar una descripciĆ³n" Display="Dynamic" />
// (...)
I have made groups work server-side with Page.Validate(group) but I wasn't aware this could be done client-side. Perhaps you need to implement a custom validation control that checks the status of each tab.
My guess is that the validation scripts are not being wired up. In your function do an alert((typeof(Page_Validators) == "undefined")) and see if it displays true. You said you are loading the tabs via ajax. You may want to see if placing a validator on the page somewhere will help wire up the validation scripts.
The other thing to watch for is Firefox and legacy rendering mode....client side just plain does not work in that scenario.
This can be done on the client side. Like this:
$('.buttonWithSameValidationGroup').bind('click', function () {
if (Page_ClientValidate($(this).attr('validationgroup'))) {
//do stuff
}
});
Sometimes you might need to add the following server side code in the Page Pre_Render method
button1.AddAttributes("validationgriup","group1");

Resources