Restrict single and double quotes in textbox in ASP.NET - c#

I want to restrict sinqles qoutes and double quotes to enter to a Textbox in Asp.net. How can i achieve it? How can i validate the textbox?

Do you use AjaxControlToolkit? if so, then use this.
<asp:TextBox runat="server" ID="TextBox1" Width="100px" />
<cc1:FilteredTextBoxExtender FilterMode="InvalidChars" ID="ftbe_TextBox1" runat="server"
TargetControlID="TextBox1" InvalidChars=""'" />
Where: cc1 is the TagName for AjaxControlToolkit
if not, do it manually
<asp:TextBox runat="server" ID="TextBox1" Width="100px" onkeypress="return restrictQuotes(event);" />
<script type="text/javascript">
function restrictQuotes(evt) {
var keyCode = evt.which ? evt.which : evt.keyCode;
return (keyCode != '"'.charCodeAt() && keyCode != "'".charCodeAt());
}
</script>

I would use javascript to do real-time validation with the textboxes onchange event. Then you can use the string.contains() method on the server-side for server-side validation.

you can add a RegularExpressionValidatorand set the ValidationExpression ='^[^\"]*$' to restrict quotes input

You could do it in javascript
<script type="text/javascript">
function fixit() {
var numberOfElements = document.theForm.elements.length;
for (x=0; x<numberOfElements; x++) {
// replace all the single, double quotes:
var curElement = window.document.theForm.elements[x];
curElement.value = curElement.value.replace(/\'/g, "'");
curElement.value = curElement.value.replace(/\"/g, """);
}
return true;
}
</script>
Then in the form you would write this
<form name='theForm' onSubmit='return fixit()'...
This code would cycle all the elements. If you want to validate a single element you could prevent the user from writing those characters
in the textbox you could do this:
<input type="text" name="foo" onkeypress="return fix(event);">
In javascript:
<script type="text/javascript">
function fix(e)
{
if(e.charCode == 34|| e.charCode == 39)
{
return false;
}
return true;
}
</script>
The last part prevents users from writing quotes and double quotes.

Related

Display Dialog Box When User Meets MaxLength of TextBox

I have a asp.net C# application. I have a TextBox that has a MaxLength set of 3000. When the user reaches the maxlength of 3000 I want a JavaScript dialog box to open and alter the user of this. I can't figure out how to do it. Can anyone help me? Thanks.
From aspdotnet-suresh:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Limit the number of characters in textbox or textarea</title>
<script type="text/javascript">
function LimtCharacters(txtMsg, CharLength, indicator)
{
chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength)
{
txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}
</script>
</head>
<body>
<div style="font-family:Verdana; font-size:13px">
Number of Characters Left:
<label id="lblcount" style="background-color:#E2EEF1;color:Red;font-weight:bold;">3000</label><br/>
<textarea id="mytextbox" rows="5" cols="25" onkeyup="LimtCharacters(this,3000,'lblcount');"></textarea>
</div>
</body>
</html>
You can use the TextChanged event of your TextBox for this. Inside your handler, you can simply check the length of the TextBox.Text property, and display a MessageBox if it reaches the maximum length like so:
Response.Write(string.Format("<script>alert('{0}');</script>", message));
You can restrict the number of characters with this JavaScript
<script language="javascript" type="text/javascript">
function limitText(Field, limitNum) {
if (Field.value.length > limitNum) {
Field.value = Field.value.substring(0, limitNum);
}
}
</script>
<asp:FormView runat="server">
<ItemTemplate>
<b>Something</b>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onKeyDown="limitText(this,3000);"
onKeyUp="limitText(this,3000);"></asp:TextBox>
</EditItemTemplate>
</asp:FormView>
Or to Display alert,
<input type="text" onkeydown="return testLength()" id="txtBox" />
function testLength(){
var e = document.getElementById('txtBox');
if(e.value.length>6)
{
alert('you have entered more than 3000 characters');
// Set value back to the first 6 characters
e.value = e.value.substring(0, 3000);
}
return true;
}

check if a hiddenfield contains more text other than commas with regular expression

i need to create an asp.net validator control that will only allow a page to post if a hiddenfield is not empty and doesnt just contain commas.
<asp:HiddenField ID="hdnProductListTip" ClientIDMode="Static" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="You must have at least one product selected against your tip" ControlToValidate="hdnProductListTip"></asp:RegularExpressionValidator>
What is the expression i need to use in the validator?
I think, you cannot use it using Regular Expression. Use Javascript for the same on Button ClientClick event.
<script language="javascript" type="text/javascript">
function CheckHiddenField() {
debugger;
var ID = document.getElementById('<%=HiddenField1.ClientID %>');
Trim(ID);
if (ID.value == '')
return false;
if (ID.value.indexOf(',') > 0) {
return false;
}
return true;
}
function Trim(ID) {
LeftTrim(ID);
RightTrim(ID);
}
function LeftTrim(Obj) {
var Trim = new RegExp('^\\s*');
Obj.value = Obj.value.replace(Trim, '');
}
function RightTrim(obj) {
var Trim = new RegExp('\\s*$');
obj.value = obj.value.replace(Trim, '');
}
</script>

"password" text in TextMode="password" in asp:TextBox

I would like to use a TextBox for a password, but before the user enters the TextBox, I want to see "enter password" as the text.
How is this usually accomplished using ASP.NET? Do I have to create second textbox and manipulate the visibility using Javascript?
If using HTML 5, just use a placeholder.
With jQuery, there is the jQuery-watermark plugin:
Capable of displaying a watermark in password input elements, showing the watermark in plain text, but then switching to password-protected (obscured) mode when focused.
You can use the AJAX watermark.
Example can be found here:
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
This is how I fixed it mine and works a dream:-
<script type="text/javascript" language="javascript">
function LoginPassword() {
document.getElementById("<%= txtTempBox.ClientID %>").style.display = "none";
document.getElementById("<%= txtPassword.ClientID %>").style.display = "";
document.getElementById("<%= txtPassword.ClientID %>").focus();
}
function LoginPassword1() {
if (document.getElementById("<%= txtPassword.ClientID %>").value == "") {
document.getElementById("<%= txtTempBox.ClientID %>").style.display = "block";
document.getElementById("<%= txtPassword.ClientID %>").style.display = "none";
}
}
<div id="dloginPassword">
<asp:Label ID="hdnLgnPassword" runat="server" Text="Password" Style="display: none;" CssClass="" />
<asp:TextBox ID="txtTempBox" runat="server" Text="Password"
onfocus="LoginPassword();" CssClass="Mainlogintextbox txtWaterMark" />
<asp:TextBox TextMode="Password" ID="txtPassword" runat="server" Style="display: none;"
onblur="LoginPassword1();" CssClass="Mainlogintextbox" />
</div>
Hope this helps?
Cheers
Steve

C# Disable/Enable Button based on Empty/Populated Text Boxes

I have a form with 5 text boxes and a button, and when the button is clicked it send the data to a SQL database. I would like the button to be disabled if any of the text boxes are null, how do I do this in C#? (I am in Visual Studio 2010 ASP.NET web app)
You need to write JavaScript/jQuery code.
Yes, What Sam said is right!!
you need to check first whether all your text boxes are empty or not.
that will be done by
If(txtbox1.text == "" || txtbox2.text == "" || txtbox3.text == "" || txtbox4.text == "" || txtbox5.text == "")
If any of the text box is empty then make the button disabled.
button1.enable = false;
If all are filled then make it as enabled.
button1.enable = true;
If you do not want to use Client side scripts, you can use validations for your controls
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1" >
</asp:RequiredFieldValidator>
Validation will trigger on postbacks.
If you have multiple controls, but you do not want to validate them all, you can use Validation Group. Check this link for using Validation Groups
use javascript setInterval on Page load if if you are using this single form on the page and check each textbox value length .. if anyone is null then disable submit button..
use jquery to disable and enable them.. check following code snippet that i have created for sample..
use this to access server control id if you are using these controls inside some container control eg. panel, contentplaceholder etc : $("#<%=button1.ClientID>%>")
$("#text1").val().length will check then length of text in textbox.. and then use jquery to enable and disable them..
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<%-- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js" type="text/javascript"></script>--%>
<%--<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7-vsdoc.js" type="text/javascript"></script>--%>
<script type="text/javascript">
$(document).ready(function () {
$("#submit").attr('disabled', 'disabled');
$("#text1").keypress(function () {
check();
});
var intv = self.setInterval("check()", 1000);
});
function check() {
if ($("#text1").val().length > 0) {
$("#submit").removeAttr('disabled');
}
else {
$("#submit").attr('disabled', 'disabled');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="text1" runat="server"></asp:TextBox>
<asp:Button ID="submit" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

Setting hidden input value in Javascript, then accessing it in codebehind

I have been trying to set the value of a hidden input by using Javascript and then access the value from within my C# codebehind. When I run the code that is copied below, the value that is assigned to assignedIDs is "", which I assume is the default value for a hidden input. If I manually set the value in the html tag, then assignedIDs is set to that value.
This behavior suggests to me that the value of the input is being reset (re-rendered?) between the onClientClick and onClick events firing.
I would appreciate any help with the matter. I have spent hours trying to solve what seems like a very simple problem.
html/javascript:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Page - Manage Tasks</title>
<script language="javascript" type="text/javascript">
function PopulateAssignedIDHiddenInput() {
var source = document.getElementById('assignedLinguistListBox');
var s = "";
var count = source.length;
for (var i = count - 1; i >= 0; i--) {
var item = source.options[i];
if (s == "") { s = source.options[i].value; }
else { s = s.concat(",",source.options[i].value); }
}
document.getElementById('assignedIDHiddenInput').Value = s;
// I have confirmed that, at this point, the value of
// the hidden input is set properly
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="EditMode" runat="server">
<table style="border: none;">
<tr>
<td>
<asp:Label ID="availableLinguistLabel" runat="server" Text="Available"></asp:Label><br />
<asp:ListBox ID="availableLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
<td>
<input type="button" name="right" value=">>"
onclick="Javascript:MoveItem('availableLinguistListBox', 'assignedLinguistListBox');" /><br /><br />
<input type="button" name="left" value="<<"
onclick="Javascript:MoveItem('assignedLinguistListBox', 'availableLinguistListBox');" />
</td>
<td>
<asp:Label ID="assignedLinguistLabel" runat="server" Text="Assigned To"></asp:Label><br />
<asp:ListBox ID="assignedLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
</tr>
</table>
//-snip-
<asp:Button ID="save_task_changes_button" runat="server" ToolTip="Click to save changes to task"
Text="Save Changes" OnClick="save_task_changes_button_click" OnClientClick="Javascript:PopulateAssignedIDHiddenInput()" />
</asp:Panel>
<!-- Hidden Inputs -->
<!-- Note that I have also tried setting runat="server" with no change -->
<input id="assignedIDHiddenInput" name="assignedIDHiddenInput" type="hidden" />
</div>
</form>
</body>
c#
protected void save_task_changes_button_click(object sender, EventArgs e)
{
string assignedIDs = Request.Form["assignedIDHiddenInput"];
// Here, assignedIDs == ""; also, Request.Params["assignedIDHiddenInput"] == ""
// -snip-
}
In javascript you need the value property to be lowercase, like this:
document.getElementById('assignedIDHiddenInput').value = s;
Then it will be set properly :) You can see an example in action here
Though if you alert the .Value it will show your value, you've actually added a new .Value property, but you haven't set the input's .value property which is what gets posted to the server. The example link above illustrates this both ways.
Also you can make it a bit faster especially if you have lots of options by using an array instead of string concatenation, like this:
var source = document.getElementById('assignedLinguistListBox');
var opts = [];
for (var i = 0; i < source.options.length; i++) {
opts.push(source.options[i].value);
}
var s = opts.join(',');
Edit: The above code is updated, CMS is right that the previous method was browser dependent, the above should now behave consistently. Also, if jQuery is an option, there are shorter ways of getting this info still, like this:
var s = $('#assignedLinguistListBox option').map(function() {
return this.value;
}).get().join(',');
$('#assignedIDHiddenInput').val(s);
You can see a working example of this here
I'm assuming ASP.NET here.
If so, your problem is the id of the control in the HTML generated by ASP.NET is not going to be "assignedIDHiddenInput" that you reference in the script. ASP.NET changes those before rendering the HTML from what you specify in the HTML page declaratively. Do a view source on the page and you will see what I mean.
Here is a way around that:
document.getElementById('<%=assignedIDHiddenInput.ClientID %>').value = s;
Update: As noted in the comments, this is only relevant if the control is set to RunAt=Server.
I think ASP.NET is calling the javascript to execute a postback on that control before your javascript function is called to populate that hidden value.
I think it's possible to disable the default postback and handle it yourself but I'm sure others can advise better.
Stick an alert() into your function there to see if it is really getting called before post-back is triggered.

Categories