im working on an .aspx page in Visual Studio.
I want to have a text box that is followed by a drop down menu.
if the user enters any input in the text box id like for it and the drop down menu to both be required before the corresponding button can be clicked.
is the best way to do this to use a RequiredFieldValidator ?
I think what you attempt to do is Conditional Validation
This question is similar to your question for Conditional Validation ASP.NET
Yes, RequiredFieldValidator would work well for your scenario. Just be sure to enable it or disable based on 'if the user enters any input in the text box'
You can create validators for both fields and onblur of the textbox enable/disable the validators using javascript.
HTML:
<asp:TextBox runat="server" ID="txt" onblur="enableVaidators();" />
Javascript:
function enableValidators()
{
var val_Test = document.getElementById('<%=val_Test.ClientID%>');
var enableValidators = true;
// Perform check on whether to enable or disable based on your scenario
ValidatorEnable(val_Test, enableValidators);
}
how about using jquery?
everything is done on the client-side:
http://docs.jquery.com/Plugins/Validation/
I would use a CustomValidator which implemented logic based on the state of the TextBox.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx
Related
I have a very long form that has to be filled out. I have maintainScrollPositionOnPostBack enabled as I have multiple controls that hide/show based on user input.
Since the form is long I'd like for the page to focus and scroll to the first control that caused validation to fail and I have the focus on validation fail option enabled. However, it seems that maintainScrollPositionOnPostBack overrides this (the control does focus but doesn't scroll up to it).
Any ideas for workarounds for this? Everything I've tried so far hasn't worked. It is an asp.net webforms project.
This is a good question and really tricky to get working. But I managed to get one version that you can try and maybe build on.
The MaintainScrollPositionOnPostback="true" -setting sets a series of javascript-events on form submit and window load and these do as you say, "overwrite" the focus set by the validator.
So what I did was add a common css-class to all validators like so:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="error" ErrorMessage="RequiredFieldValidator" SetFocusOnError="true"
EnableClientScript="false" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
And then I added another eventlistener to window.load (note we need to leave also the one that Asp.Net has added so we cannot do windows.load = function...):
<script>
window.addEventListener("load", function () {
var el = document.getElementsByClassName("error");
if (el.length > 0) {
window.location.hash = "#" + el[0].id;
}
});
</script>
Here you might benefit from jQuery use to be able to support more browsers but addEventListener is pretty well supported.
The script searches for the errormessage and focus on that by it's id with anchor. Javascript has focus-method but it's for form elements so that's why this workaround.
Hope this helps!
I have a page with a repeater containing RadioButtonLists which have requiredFieldValidators attached to them. I need to keep the RFV next to the control (it's the only way I can get it to work to be honest!)
However, the form is made up of a few sections contained in an accordion. This means that when the form is submitted, the item that has failed validation may not be visible, so the user won't know where the error is.
Is there a way I can also have a message by the submit button which is triggered by an RFV changing saying "please go back and check your answers" or something? I guess I'd need to use JQuery / JavaScript as it would be clientside.
There is a special ValidationSummary control for that:
<asp:ValidationSummary ID="Summary" runat="server"
DisplayMode="SingleParagraph"
HeaderText="Please go back and check your answers" />
This control is used to summarize all validation errors on the page.
Try "ValidationSummary". look for example from here.
http://www.w3schools.com/aspnet/control_validationsummary.asp
I have an ASP.NET page that contains a form and a button. In order to use the OnKeyPress and a javascript function (to stop the user from using the enter key and without adding a FilteredTextBoxExtender) attribute I had to change the <asp:Textbox> to an <input> with type="text".
Is this considered bad practice? Or are there valid situtations where should be used?
To ensure this question isn't subjective - are there any other ways to prevent the user using the enter key when typing in an ASP.NET textbox? (without putting code in the code behind)
In General you should use Asp.Net control only when is strictly required ad the classic HTML are much faster as they don't need any server elaboration to be rendered
If you want your input to be accessed by .NET code-behind then it's considered best practice to use the TextBox control. You can put a runat=server on an input, but only when you must.
If it were me, I'd use the , add an ID and set the ClientIDMode="Static" if possible, or add a class with CssClass="class", then use jQuery to handle the onKeyPress even with something like this:
$('.class').on('change', function() {
});
You do not need to change the control type in order to use client side events in javascript.
The control has a ClientId property that can be used for binding the event to (using getElementById, for example).
You can add JavaScript to <asp:TextBox />. You can either attach the JavaScript using the ClientID of the control, or you can add it in the codebehind using
MyTextBox.Attributes.Add("onKeyPress", "myJavaScriptFunction()");
You should just use the ClientID of your asp:TextBox
here is an example using jQuery :
<asp:TextBox ID="inputTB" runat="server"></asp:TextBox>
<script language="javascript" type="text/javascript">
$('#<%=inputTB.ClientID%>').keypress(function (e) {
if (e.which == 13) // return key
{
return false;
}
});
</script>
I want to develop an application in asp.net with C#.
In that application there are one text box and one label.
I want the following functionality:
When I press any key in textbox then I should get this value on .cs page i.e; code behind. And from .cs page I want to add this value to the label.
The problem is that there is no keypress event for an asp textbox and if I take a html text box then I don't get its value on .cs page
How can I come out with this problem?
Because a keypress on a textbox is a client side event but you want to perform server-side processing you will need to use AJAX requests.
You may find the following useful:
AJAX Toolit
Using Jquery to call asp.net page methods
In asp.net the TextBox will have TextChanged event but you will need to enable post back for the button and the event will fire when you tab out of the TextBox.
For the task you want either use javascript or add a button and when this button is do what you want.
I don't think this is a good aproach in web app., In this way you will end with a lot of post-backs.
However, if you still want this functionality. Texbox has TextChanges event, and if you also change the textboxs's AutoPostBack property to true you will get something close, but you will still have to move a currsor.
But it is still a terible solution. Why don't you simply use a button that fires click event instead?
Alternative solution is to use Ajax or javaScript,..
You can simply create a JavaScript-Method for this.
Your Textbox:
<asp:TextBox ID="textBox" runat="server" onkeydown="onFilterTextChanged()">
</asp:TextBox>
Your JavaScript, do a TimeOut to not do this every 0,0001 secs.
function onFilterTextChanged() {
if (timeoutID)
window.clearTimeout(timeoutID);
timeoutID = window.setTimeout(updateFilterText, 600);
}
Send the Values to the CodeBehind, textis your TextBox-Text.
function updateFilterText() {
var text = document.getElementById("<%=textBox.ClientID %>").value;
__doPostBack("<%=textBox.ClientID%>", "CommandArg" + text);
}
You won't need to do as many PostBacks as with the native TextChanged-Event and you can simply use this e.g. for Auto-Extender-Plugins. Pack the TextBox into an UpdatePanel and you're good to go!
Unless of course you do not NEED to go back to the server, in which case just set the labeltext in updateFilterText.
How to disallow use of double quotes " in a textbox
Use String.Contains()
Since you can never control what users do the client you might as well just check it on the server, so you would probably use code something like:
if (textBox1.Text.Contains("\""))
{
Response.Write("Dey aint no way I'm letting you type that!");
}
use RegularExpressionValidator and set the ValidationExpression='^[^\"]*$', that will allow anything, including empty, other than "
If you don't want users to be able to type quotes in the textbox in the first place, consider using a FilteredTextBox from the AJAX Control Toolkit.
Use the RegularExpressionValidator for your page input validation. The .NET validation controls will verify your users' input on both sides, the client-side, and the server-side which is important if the user has disabled JavaScript. This article might also help you to implement the validation of your ASP.NET server controls.
Please don't do this just with JavaScript or AJAX. Always perform a server-side input validation! Especially if you are writing the users' input back into a database (SQL Injections).
You haven't specified if you're using webforms or MVC, so I'm gonna throw a couple things a'cha.
First off, here's the Regex you'll use in either situation. ^[^\"]*$
First for WebForms
<asp:TextBox runat="server" id="TextBox1" />
<asp:RegularExpressionValidator runat="server" id="Regex1" controltovalidate="TextBox1" validationexpression="^[^\"]*$" errormessage="Nope!" />
<!-- This will give you client AND server side validation capabilities-->
To ensure you're valid on the SERVER SIDE, you add this to your form submit method
If Page.IsValid Then
''# submit the form
Else
''# your form was not entered properly.
''# Even if the user disables Javascript, we're gonna catch them here
End If
In MVC you should definitely use DataAnnotations on your ViewModel
NOTE: DataAnnotations can also be use for WebForms if you're planning on doing a lot of repeat ctrl + C and ctrl + V
''# fix SO code coloring
''# this is in the view model
<RegularExpression("^[^\"]*$", ErrorMessage:="Nope")>
Public Property TextBox1 As String ''# don't actually call it TextBox1 of course
And in your controller "Post" action, you wanna add the following
If ModelState.IsValid Then
''# submit the form
Else
''# your form was not entered properly.
''# Even if the user disables Javascript, we're gonna catch them here
End If