how to reset input field after validation fails? - asp.net

I have a validator for a date input field. If the input is not in the MM/DD/YYYY format then it should throw an error and clear the input. I have tried Text="" property, but that doesn't work. And setFocusOnError is only working once.If I hit tab twice the field is losing foucs . Any ideas?
<asp:RegularExpressionValidator ID="startDateValidator" Display="Dynamic"
ControlToValidate="dateStartDate" ValidationExpression="([0-9]|1[012])[/]([0-9]|[12][0-9]|3[01])[/](19|20)\d\d"
ErrorMessage="Start Date should be in MM/DD/YYYY format" runat="server" SetFocusOnError="true"
/>
EDIT: I want to know if this is possible using asp's validator controls.And why SetFocusOnError is not working as it's supposed to?

You should always validate on server side, additionally you can of course validate on client side (usability).
You can clear the textbox via javascript, but consider a user could have disabled javascript. That's also why you should always validate on server side.
<script language=JavaScript>
<!--
function clear_textbox()
{
document.text_form.u_input.value = "";
}
-->
</script>
You can run this script, you need to change u_input to your controls name.

Related

ValidationSettings for aspxtextbox to validate decimal

I have written a regular expression for AspxTextBox to validate decimal value as follows
<dx:ASPxTextBox ID="txtDecimal" runat="server">
<ValidationSettings ValidationGroup="g" RegularExpression-ValidationExpression="^\d+(\.\d{1,2})?$">
</ValidationSettings>
</dx:ASPxTextBox>
When I am entering the digits in the textbox directly it is validating as per required, but I have a group of buttons with 0-9 and a . button where user can input the text using those buttons, on clicking buttons and appending text in the textbox validation is unable to fire even if I enter wrong input, what might be the problem can some one help me
I suppose that DevEx library uses on change event to execute validation.
OnChange (and other Javascript events) are executed when control value is changed during user interaction and not when you change value programatically.
So, you need to execute it manually:
<dx:ASPxTextBox ID="txtDecimal" runat="server" ClientInstanceName="tb">
<ValidationSettings ValidationGroup="g" RegularExpression-ValidationExpression="^\d+(\.\d{1,2})?$"/>
</dx:ASPxTextBox>
<input type="button" onclick="tb.SetValue('10xyz');tb.Validate();"/>

How to show regular expression validation's message after button click only?

Below is my html code. I have a email textbox and there is a login button. I have added a required field validator and regular expression validator for email textbox.
The problem is that when I type some thing in the email textbox browser's auto suggestion shows some list of emails. When I select any of those emails by using down arrow key and enter key it shows the error message for regular expression validation even though email is in proper format.
<asp:RequiredFieldValidator ID="reqValUserName" runat="server"
ErrorMessage="Email is required!"
ControlToValidate="txtUserName"
ValidationGroup="validateCredential"
Display="Dynamic">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regValUserName" runat="server"
ErrorMessage="Incorrect format!"
ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="validateCredential"
Display="Static">
</asp:RegularExpressionValidator>
<asp:TextBox ID="txtUserName" runat="server"
TabIndex="1" CssClass="inputCredential" MaxLength="60"
AccessKey="E"
ValidationGroup="validateCredential">
</asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CssClass="btnPrimary"
Text="Login" onclick="btnLogin_Click"
ValidationGroup="validateCredential"/>
In this image as you see if I select the email from the suggestion and press enter it is showing the wrong email validation message.
Can anyone please let me know, how to stop this kind of message display?
If there is any clarification needed regarding the question then please add it as a comment.
You could add the EnableClientValidation="false" attribute to the regex validator so that it only checks the format on the server after the other validators have been passed.
Or follow the advice here:
What determines the order validators fire in?
Also add regular expression validator
for email text box
<asp:RegularExpressionValidator ID="regtxtPrimaryEmail" runat="server" ControlToValidate="txtEmailId"
Display="Dynamic" CssClass="cssVal" ToolTip="Invalid email." ValidationGroup="registration"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
Then it will not submit until the email format correct.
It seems your some controls has autopostback="true" and your these controls are in update panel if not then what you can do is..Remove the display properties of all the validation controls and on btnLogin_Click Event call Validate(); Method.
Also read more In Depth detail on Validators on MSDN
you'll certainly get your answer....
Thanks for all your answers and suggestions.
Below is what I have done after going through all the answers.
<asp:RegularExpressionValidator ID="regValUserName" runat="server"
ErrorMessage="Incorrect format!"
ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="validateCredential"
Display="Dynamic" EnableClientScript="false">
</asp:RegularExpressionValidator>
As you can see, I have added EnableClientScript="false" so that the error message will not be shown when I type half of email and select from auto suggestion and press enter.
Now the problem was it was always checking for whether entered credentials are correct of not as it was doing validation in server side. So I had some unnecessary code execution and database interaction.
So in click event handler of login button I did following change.
if(Page.IsValid)
{
// My credential check code
}
So the above block of code will run code for checking correctness of entered credentials only if they are in proper format.
But I am still looking for a better answer. This is only a work around. Because when it comes to performance server side validation can never match client side validation. Here I am compromising with usability. As I want user to be notified immediately after he/she enters a wrong formatted email. This can be achieved by using javascript, but I wonder if there is any way we can achieve it using validator controls..
This is happening because the client-side REV is validating on the partial input. For example, in the above illustration, the REV is validating "r" as its input. In order to verify this,
type in the entire email address "rupeshn#aol.com" >> then
select the suggested email using the down arrow >> then
hit the enter key.
The REV will not complain this time.
As for the solution: implement the REV in javascript. Add a label next to the textbox for error message. Call the js when the cursor exits the textbox. If the validation fails, find the label in the js and add the error message.
Just see the properties of the validator there you will find 'Display' property under Appearance section, set it to dynamic and VOLA!!

RequiredFieldValidator have to click twice

I have run into the same problem as described here.
Only the question is marked as answered with only an explanation as to why you may have to click twice when using a RequiredFieldValidator on input fields - once as the blur of a textbox(for example) will correct the validation and then again to actually post the form.
I don't want to have to click a button twice! Does anyone know a solution or workaround to this?
You could add EnableClientScript=false to the validator.
That prevents the client-side validation, so you will always get a postback (which may not exactly be what you want, though). The validation will still be done, just server-side.
Be sure to wrap the button-click logic in a if (Page.IsValid) { ... }, to check the status of the validators.
Apologies for not posting code previously I assumed this to be a standard problem with the RequiredFieldValidator, but have since realised my particular problem was coming from a CompareValidator, used to ensure entered passwords matched.
The CompareValidator was causing the issue that I described, causing me to have to click away from the field to blur and validate, before being able to click on the post button.
I'm not sure why but changing the Display of the CompareValidator from Dynamic to Static has cleared the problem up.
If the validator is Display="Dynamic", and the appearance of the error message causes the submit button to move, then the MouseUp event is not received by the submit button. In this case, the validation fires and clears the error message, but the submit button does not fire. To solve the problem, either set the the validators to be Display="Static", or rearrange the form so that the submit button does not move when error messages appear.
Here's a way to reserve about one, vertical line of space for a dynamic validation message:
<div style="height:1.5em;overflow:visible;">
<asp:RequiredFieldValidator ID="R1" runat="server"
ErrorMessage="Name is required" ControlToValidate="TextBoxName"
Display="Dynamic"></asp:RequiredFieldValidator>
</div>
I did not find it necessary to set EnableClientScript="false", although that did help for a CustomValidator that had no client-side validation function implemented.
Posting your code is always a good idea, That way we could run your code in a test environment and modify it to ensure it works before posting our answer.
I would suggest adding
causesValidation="true"
to your button to see if that works.
I have a better idea.
Add Text="" to textbox Control.
Add InitialValue="" to Validator Control.
What it will do, when it will be posting, it will find the value of the text box is still the initail value and it will throw an error and the form will not be posted.
Try this:
<asp:RequiredFieldValidator ID="reqFieldCloseComment" ControlToValidate="tbCloseComment" ValidationGroup="ChangeStatus" ErrorMessage="Please enter a reason" Display="Dynamic" runat="server" InitialValue=""></asp:RequiredFieldValidator>
<asp:TextBox ID="tbCloseComment" runat="server" CausesValidation="true" TextMode="MultiLine" Height="107px" Width="400px" Text=""></asp:TextBox>
<asp:Button ID="btnCloseRequestFinal" Text="Finish" CssClass="CloseReqButton" runat="server" ValidationGroup="ChangeStatus" />
Here is code that is working fine for me and helping to get rid of double click.
<asp:TextBox ID="TextBox1" runat="server" autocomplete="off"
Enabled="true" MaxLength="20" onfocus="SetActiveControl(this);" Text=""
CausesValidation="true" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1" Display="Static" ErrorMessage="Ha!" SetFocusOnError="True" EnableClientScript="true" ForeColor="" InitialValue="" />
$(function() {
$("input.btn").on("click",function(){
if(Page_BlockSubmit == true) {Page_BlockSubmit = false};
})
});
Page_BlockSubmit is a JS variable defined by the js generated from code behind when you define the validator . I haven't went deeper to know why MS need this variable, but the scenario is:
the first click will make Page_BlockSubmit become false.
the second click will check the value of Page_BlockSubmit and return true.
if you implemented the code I posted, every time you click the button, the variable will be set as false which will trigger the submit at every click.
And, you can use google chrome to trace the value of Page_BlockSubmit.

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 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.

Resources