var targetControl = this.NamingContainer.FindControl(this.ControlToValidate) as TextBox; if (targetControl != null) { var maxLength = targetControl.MaxLength; writer.AddAttribute("maxlength", maxLength.ToString()); } } }
protected override void OnPreRender(EventArgs e) { var script = @" function MaxLengthValidator_GetNonNationalLength(text) { if (!text){ return 0; } var length = 0; for (var i = 0; i < text.length; i++) { var charCode = text.charCodeAt(i); length++; if (charCode > 255) { length++; } } return length; } function MaxLengthValidator_Validate(val) { if (!val) { return true; } var targetID = val.TargetControlID; if (!targetID) { return true; } var nonNational = val.ValidateForNonNationalField; if (!nonNational) { return true; } var target = document.getElementById(targetID); if (!target) { return true; } var maxLength = val.maxlength; if (!maxLength || isNaN(maxLength)) { return true; } var targetValue = target.value; if (!targetValue) { return true; } var realLength = targetValue.length; if (nonNational == 'true') { realLength = MaxLengthValidator_GetNonNationalLength(targetValue); } return realLength <= parseInt(maxLength); }"; ScriptManager.RegisterClientScriptBlock(this, typeof(MaxLengthValidator), "MaxLengthValidator_Validate", script, true);