How to set maxlength for multiline TextBox? - asp.net

When using a MultiLine TextBox (which generates a TextArea) setting the MaxLength property has no effect. What is the best workaround? I'd like to get basic, intended functionality with minimum of ugly javascript etc. Just prevent user from entering more than max number of characters.

If you don't care about older browsers (see supported browsers here),
you can set MaxLength normally like this
<asp:TextBox ID="txt1" runat="server" TextMode="MultiLine" MaxLength="100" />
and force it to be printed out to the HTML
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txt1.Attributes.Add("maxlength", txt1.MaxLength.ToString());
}

If you want to let the user know if he exceeded the amount of characters as he writes, you could use a javascript function attached to keypress event. This function would test the length of the input and cancel the character rendering if the maxlenght was reached.
Another option is to use RegularExpressionValidator control to validate the input on submit.
In my opinion, the first option is much more better.
I'm not adding any code since google is full of examples for all tastes, this is a very common task.
Here you have a sample search that might help.

Hey pukipuki you can do as follows:
<asp:TextBox ID="txtValue" runat="server"TextMode="MultiLine" Rows="10"Columns="50"></asp:TextBox>
$(document).ready(function(){
var MaxLength = 250;
$('#txtValue').keypress(function(e)
{
if ($(this).val().length >= MaxLength)
{
e.preventDefault();
}
});});
You can see more in this following link:
http://jquerybyexample.blogspot.in/2010/10/set-max-length-for-aspnet-multiline.html

Here's a cross browser solution :
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtPurpose" Columns="50" Rows="2" onkeypress="return isokmaxlength(event,this,255);" ClientIDMode="static"></asp:TextBox>
Javascript :
function isokmaxlength(e,val,maxlengt) {
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
if (!(charCode == 44 || charCode == 46 || charCode == 0 || charCode == 8 || (val.value.length < maxlengt))) {
return false;
}
}
You have to think about the Copy and Paste. This is a little bit tricky, I simply disable it with Jquery. But you can create your own function to do more complex verification. But in my case, copy and paste is not allowed.
Jquery to disable copy and paste :
jQuery(function ($) {
$("#txtPurpose").bind({
paste: function (e) {
e.preventDefault();
}
});
});

If you are using a model object bind to that textbox you can use DataAnnotations attributes to set the maxlength of that property. I'm based on MVC about that but it should work for ASP.NET too!
This way you don't mess with any Javascript or setting anything in the markup.

Try this..
Dim script As String = ""
script = script + " <script type='text/javascript'> function CheckLength(obj) {"
script = script + " var object = document.getElementById(obj);"
script = script + " if (object.value.length > 5) {"
script = script + " object.focus();"
script = script + " object.value = object.value.substring(0, 5); "
script = script + " object.scrollTop = object.scrollHeight; "
script = script + " return false;"
script = script + " }"
script = script + " return true;"
script = script + " }</script>"
Dim b As New TextBox()
b.ID = "btnSomeButton"
b.TextMode = TextBoxMode.MultiLine
Mypanel.Controls.Add(b)
b.Attributes.Add("onkeyup", "return CheckLength('" & b.ClientID & "');")
Page.ClientScript.RegisterStartupScript(Page.GetType(), "key", script, False)

To force asp.net to send the maxlength attribute for all multiline textboxes on a page or a whole site,
building on Aximili's answer above:
Create a function to get all the controls on the page:
I use the control extension method from David Findley
https://weblogs.asp.net/dfindley/linq-the-uber-findcontrol
and referenced in this SO post
Loop through all controls on asp.net webpage
namespace xyz.Extensions
{
public static class PageExtensions
{
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
}
}
In the page or master page
Make sure to reference the namespace for the extension method in step 1.
Put the following code in the Page_Load function:
if (!IsPostBack){
//force textareas to display maxlength attribute
Page.Controls.All().OfType<TextBox>().ToList()
.Where(x => x.TextMode == TextBoxMode.MultiLine && x.MaxLength > 0)
.ToList().ForEach(t => t.Attributes.Add("maxlength", t.MaxLength.ToString()));
}

Related

CustomValidator using CustomValidationScript

I have an ASP.NET TextBox with a CustomValidation control that invokes client side validation script.
<asp:TextBox ID="txtSubsContrRbtAmt" runat="server"
CssClass="textEntry NumericInput" Width="150px"
Text="" onKeyUp="SumValues();" MaxLength="16"></asp:TextBox>
<asp:CustomValidator ID="cvalSubsContrRbtAmt" runat="server" ClientValidationFunction="ValidatetxtSubsContrRbtAmt"
ControlToValidate="txtSubsContrRbtAmt" CssClass="errlable" ErrorMessage="Max Decimals = 7"
SetFocusOnError="True" ValidationGroup="CarbsAdd"></asp:CustomValidator>
Here's the Client script:
function ValidatetxtSubsContrRbtAmt(source, args) {
var txtSubsContrRbtAmt = document.getElementById("<%=txtSubsContrRbtAmt.ClientID%>");
var amount = txtSubsContrRbtAmt.value;
args.IsValid = ValidAmount(amount);
if (!args.IsValid)
txtSubsContrRbtAmt.focus();
}
function ValidAmount(amount) {
if (isNumber(amount)) {
return (RoundToXDecimalPlaces(amount, 7) == amount);
}
else {
return true;
}
In the ValidatetxtSubsContrRbtAmt function, the "source" parameter is the CustomValidator. That control has a property "ControlToValidate." If I can get to it, I can programmatically retrieve the value from that control and not have to have a separate function to validate each textbox.
jQuery is too much for me at this point, I'm looking for a plain old Javascript approach, please.
You don't have to get the text box. You can get the value from args.Value. The focus should be set automatically if you set SetFocusOnError="true".
function ValidatetxtSubsContrRbtAmt(source, args) {
var amount = args.Value;
args.IsValid = ValidAmount(amount);
}
You should be able to get to the control from the source object.
function ValidatetxtSubsContrRbtAmt(source, args) {
var controlToFocusOn = source.ControlToValidate;
you can switch that out with "document.getElementByID()" to get the ID or whatever attribute you need
var controlId = document.getElementById(source.ControlToValidate).id;
}
now you can focus or do what you need with the control. I had to access the the actual ControlToValidate earlier today from a CustomValidator.

asp.net - manually run client-side validation code from another event

I want to run whatever client-side validation routine is hooked up to a particular text input element.
The validation has been set up using CustomValidator:
<asp:textbox id="AddEstTime" runat="server" Width="55px"></asp:textbox><br />
<asp:CustomValidator ID="AddEstTimeCustomValidator" ClientValidationFunction="AddEstTimeCustomValidator_ClientValidate" OnServerValidate="AddEstTimeCustomValidator_ServerValidate" ErrorMessage="Please enter a time" ControlToValidate="AddEstTime" runat="server" Display="Dynamic" ValidateEmptyText="true"/>
<asp:CheckBox ID="AddIsTM" runat="server" Text="T&M" />
and the javascript:
function AddEstTimeCustomValidator_ClientValidate(sender, args) {
var checkbox = $("input[id$='IsTM']");
args.IsValid = checkbox.is(":checked") || args.Value.match(/^\d+$/);
}
When the CheckBox "AddIsTM" state changes, I want to revalidate the textbox "AddEstTime", using its hooked-up CustomValidator "AddEstTimeCustomValidator".
I am aware of focus -> add a character refocus -> remove character. I am trying to find a more correct way. New to asp.NET.
After looking through the Microsoft client-side code, I came up with this which seems to work:
// client-side validation of one user-control.
// pass in jquery object with the validation control
function ValidateOneElement(passedValidator) {
if (typeof (Page_Validators) == "undefined") {
return;
}
$.each(Page_Validators, function (index, value) {
if ($(value).attr("id") == passedValidator.attr("id")) {
ValidatorValidate(value, null, null);
}
});
}
This was after examining the Page_ClientValidate function:
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
return Page_IsValid;
}
thx sennett (voted)
i just ran the simplest JS
Page_ClientValidate();
if you have a validation group then is
Page_ClientValidate("validationGroupName")
If you want stick with ASP.NET validators eventually you can abuse Validation Groups, but I think that this approach will give you nothing but trouble. Other option is to use jQuery on the client (nice list) only then you will have to duplicate validation on the server side, or to avoid that call server methods from client validations.

How to go about validating AJAX cascading drop down lists

I am using the AJAX Cascading drop down list but want to add event validation e.g. the compare validators.
As the cascading drop down list requires the page event validation to be disabled what is the best way to do the validation?
Thanks
Andy
Validation Attempt:
I have tried to use a custom validator which calls a Javascript function but it doesnt seem to be picking up the control. I get the following error Microsoft JScript runtime error: Object required
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("ddlCategory");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if (iValue == "Select Category")
{
arguments.IsValid = true;
}
else
{
arguments.IsValid = false;
}
}
}
The mark-up for the custom validator is
<asp:CustomValidator ID="valcustCategory" runat="server" CssClass="error" Display="Dynamic" ValidationGroup="DirectHire" ClientValidationFunction="ValidateCostCentCat"
ErrorMessage="Please select a Cost Centre Category from the drop down list provided.">!</asp:CustomValidator>
Read This: http://www.w3schools.com/PHP/php_ajax_database.asp
The example demostrate how to select a
value from a dropdown box sent it via
AJAX and get back the responce!
in the middle you can do all the
Validation that you want!
UPDATED with code just for fun! ;-)
Assuming your select is
<asp:DropDownList ID="CategoryDropDownList" runat="server">
Then you function look like this:
function ValidateCostCentCat(source, arguments)
{
var countryList = document.getElementById("CategoryDropDownList");
if (null != countryList)
{
var iValue = countryList.options[countryList.selectedIndex].value;
if ( iValue == "Select Category" ) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
}
This must work as expected!
hope this help!

asp.net javascript

I am writing a javascript in asp.net server side (with in a button click event), this script is called if the user id and password matches and it supposed to close current window and open welcome page, but it is not happening. Below is my code, can anyone help me figure out what is the problem?
protected void okbtn_Click(object sender, EventArgs e)
{
account.txtuser = txtuid.Text;
account.txtpwd = txtupwd.Text;
account.login();
if (account.data == true)
{
string script = "<script language='javascript' type='text/javascript'>function f11(){window.close();var strLocation ;var strProfileID ;if (top.opener == null){strLocation = 'YourAccount.aspx';window.location = strLocation;}else{strLocation = 'http://' + top.opener.location.hostname+':'+ window.location.port + '/SendMail/' + 'YourAccount.aspx';top.opener.location = strLocation;top.opener.focus();}}</script>";
ClientScript.RegisterStartupScript(GetType(),"abc", script, true);
}
else
{
Label1.Text = "Invalid user name or password";
}
}
Add a OnClientClick event instead. For example:
<asp:Button id="okbtn" runat="server" text="OK" OnClientClick="window.close();" />
As for registering the startup script, you'd probably want to do this on Page_Load.
ClientScript.RegisterStartupScript(GetType(), "abc", script, true);
if you pass true argument at the end of the function parameters you don't need to add tags in your javascript codes because true means " tags will automatically wrap your javascript code"
Try in this way. If it doesn't help, please let us know.
Don't include <script></script> tag.
string script = "setTimeout(f11,10); function f11(){ window.close();}";
ClientScript.RegisterStartupScript(GetType(), "abc", script, true);

Disable Validator but Validator Callout still shows and causes validation

I'm trying to validate that a certain increment of a product was entered in the product qty textbox that is in a repeater. The problem is that the increment is different for every product, so I need that as a variable for each call to validate it (which I don't think you can do with a custom validator), and I need it client side with a ValidatorCalloutExtender. The best solution i have come up with is to trigger a RegEx validator that will evaluate false via my own javascript (another validator takes care of making sure its a valid number). The problem is that with the ValidatorCalloutExtender, when I disable the validator it still marks it as invalid (the textbox flashes white then turns yellow again (meaning its invalid), even though I placed JavaScript alerts and I know the validator is getting disabled. Anyone have any ideas as to whats going on here? Here is the code. Thanks!
PS: Everything works fine w/out the validatorCalloutExtender, but I really need the Callout Extender!
The validators:
<asp:RegularExpressionValidator ID="ProductIncrementValidator" runat="server"
ControlToValidate="ProductQtyTxt"
ErrorMessage="Please enter a valid increment"
ValidationExpression="^triggerthisvalidation$"
Enabled="false"
Display="Dynamic"
SetFocusOnError="true"
ValidationGroup="productValidation">
</asp:RegularExpressionValidator>
<ajax:ValidatorCalloutExtender ID="ProductIncrementVE" runat="server"
TargetControlID="ProductIncrementValidator"
HighlightCssClass="validator"
WarningIconImageUrl="~/img/blank.gif">
</ajax:ValidatorCalloutExtender>
When Databinding the product:
Dim productQtyTxt As TextBox
productQtyTxt = CType(e.Item.FindControl("ProductQtyTxt"), TextBox)
Dim incrementValidator As RegularExpressionValidator
incrementValidator = CType(e.Item.FindControl("ProductIncrementValidator"), RegularExpressionValidator)
incrementValidator.ErrorMessage = "Please enter an increment of " & product.OrderIncrement.ToString()
' Add item qty increment check
productQtyTxt.Attributes.Add("onChange", "javascript:checkIncrement('" _
& productQtyTxt.ClientID & "', " _
& product.OrderIncrement & ", '" _
& incrementValidator.ClientID & "')")
The Javascript:
function checkIncrement(textboxID, incrementQty, validatorID) {
var textbox = $get(textboxID);
var incrementValidator = $get(validatorID);
var qtyEntered = textbox.value;
if ((qtyEntered % incrementQty) != 0) {
ValidatorEnable(incrementValidator, true);
alert("not valid");
return;
}
else {
ValidatorEnable(incrementValidator, false);
alert("valid");
return;
}
}
1.Set CSS class for ValidatorCalloutExtender:
<style id = "style1" type="text/css">
.CustomValidator
{
position: relative;
margin-left: -80px;
margin-top: 8px;
display: inherit;
}
</style>
<ajax:ValidatorCalloutExtender ID="ProductIncrementVE" runat="server"
TargetControlID="ProductIncrementValidator"
HighlightCssClass="validator"
WarningIconImageUrl="~/img/blank.gif"
CssClass="CustomValidator">
</ajax:ValidatorCalloutExtender>
2 . Use JavaScript to alter this CSS class when needed. Set display = none:
function alterDisplay(type) {
var styleSheet, cssRule;
if (document.styleSheets) {
styleSheet = document.styleSheets[index1];
if (styleSheet) {
if (styleSheet.cssRules)
cssRule = styleSheet.cssRules[index2]; // Firefox
else if (styleSheet.rules)
cssRule = styleSheet.rules[index2]; // IE
if (cssRule) {
cssRule.style.display = type;
}
}
}
}
Note: the index1 and index2 may be difference from pages, it's up to your declaration. You can use IE debugger to find our the correctly indexs.
I had the same problem, i solved with something like this
if ((qtyEntered % incrementQty) != 0) {
ValidatorEnable(incrementValidator, true);
$("#" + validatorID + "_ValidatorCalloutExtender_popupTable").show();
alert("not valid");
return;
}
else {
ValidatorEnable(incrementValidator, false);
$("#" + validatorID + "_ValidatorCalloutExtender_popupTable").hide();
alert("valid");
return;
}
Hope this helps someone.

Resources