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

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.

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

Server side validation

I am having an issue with the requiredfieldvalidator control not working on an ASP.net page. I have completed the attributes of that field properly, but when I test it, the postback is allowed to happen even if the field in question is blank.
So I want to do server side validation instead. What is the best way to do that? In the event that caused the postback? Also, if I find out the field is blank, how do I get the user back to the screen with all other values they placed on other fields intact and a message saying "This field cannot be blank".
EDIT:
This is the code:
<asp:TextBox ID="fName" TabIndex="1" runat="server" Width="221px" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameRequiredFieldValidator" runat="server" ControlToValidate="fName" InitialValue="" ErrorMessage="Filter Name cannot be blank." ToolTip="Filter Name cannot be blank.">*</asp:RequiredFieldValidator>
You need to provide the markup for your Button / Link control as well.
The 'CausesValidation' attribute is not supposed to be used on TextBox controls.
The button you click needs to have that attribute set to "True".
Please provide that markup and then I can advise on the alternate server side validation.
To enable Client-side Validation, set the EnableClientScript="true" on the RequiredFieldValidator.
You should also always validate on the server side too. But the RequiredFieldValidator doesn't let you do any special-handling server-side. Just check if Page.IsValid(). This will return false if the field is not supplied.
If you want to do custom validation, use a CustomValidator.

How do you reenable a validation control w/o it simultaneously performing an immediate validation?

When I called this function to enable a validator from client javascript:
`ValidatorEnable(document.getElementById('<%=valPassportOtherText.ClientID%>'), true); //enable` validation control
the required validation control immediately performed it validation, found the value in the associated text box blank and set focus to the textbox (because SetFocusOnError was set to true). As a result, the side effect was that focus was shifted to the control that was associated with the Validation control, i teh example, txtSpecifyOccupation.
<asp:TextBox ID="txtSpecifyOccupation" runat="server" AutoCompleteType="Disabled"
CssClass="DefaultTextBox DefaultWidth" MaxLength="24" Rows="2"></asp:TextBox>
<asp:RequiredFieldValidator ID="valSpecifyOccupation" runat="server" ControlToValidate="txtSpecifyOccupation"
ErrorMessage="1.14b Please specify your <b>Occupation</b>"
SetFocusOnError="True"> Required</asp:RequiredFieldValidator>
Perhaps there is a way to enable the (required) validator without having it simultaneously perform the validation (at least until the user has tabbed off of it?)
I'd like validation of the txtSpecifyOccupation textbox to occur only on a Page submit or when the user has tabbed of the required txtSpecifyoccupation textbox.
How can I achieve this?
Don't call the ValidatorEnable method. Instead, get a reference to teh validation control and simply set its "enabled" property as desired.
To clear the validation control's error text, set the innerText property to "".

asp.net sanitizing user input

Does asp.net have a built in mechanism that can sanitize all textbox input instead of redirecting to the error page?
I have a textbox input where a user can enter a name, but if they try to enter and <> tags the page automatically throws an error. I just want to handle this error in a user friendly way.
You'll want to look at the AntiXSS library for that. It's a dll so it's easy to drop in and start using it.
The download is at CodePlex.
You can use the ASP.NET RegularExpressionValidator control with a pattern like: ^[^<>]*$
<asp:RegularExpressionValidator ID="rev" runat="server"
ControlToValidate="txtBox"
ErrorMessage="The <> tags are not allowed!"
ValidationExpression="[^<>]*" />
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtBox"
ErrorMessage="Value can't be empty" />
The RequiredFieldValidator is used in conjunction with the RegularExpressionValidator to prevent blank entries. If that textbox is optional, and only needs to be validated when something is entered, then you don't have to use the RequiredFieldValidator.
The benefit of doing it this way is that the error can be handled gracefully and the user can be notified on the same page.
However, if you need to do this for many textboxes and you just want to present something nicer than the error page, you could handle the ValidateRequest error to provide a friendlier message and keep the user on the same page (not just replace it with a custom error page). For more info, check out Kirk Evans' post: Handling ValidateRequest errors within a Page (refer to the section titled Overriding the OnError Method).
Read this for a step-by-step: http://yourtahir.wordpress.com/2008/03/28/aspnet-not-allow-html-in-text-boxserver-error-in-application-a-potentialy-dangerous-requestform-value-was-detected/
You have to do some web.config work.
ASP.net has validation controls
[http://msdn.microsoft.com/en-us/library/7kh55542.aspx][1]
Also there is Mark Down Editor which is a control that strips out html tags etc.

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