Thursday, January 24, 2013

String Truncate

PROBLEM: The .NET framework doesn't have a truncate method for strings.  Substring will fail if you're not careful (i.e. if you don't check that the string has at least as many characters at the truncation length)

SOLUTION: Add a Truncate extension method for the string class that does the boring checks (length, null - some other examples don't include the null check, etc) for you each time.


        /// <summary>
        /// Ensure that a string is no longer than a specified maximum number of characters.
        /// This string extension method has been written because there is no string truncate method
        /// in the .NET framework and Substring will throw an exception if the length you enter is
        /// longer than the length of the string.
        /// </summary>
        /// <param name="originalString"></param>
        /// <param name="maximumLength"></param>
        /// <returns></returns>
        public static string Truncate(this String originalString, int maximumLength)
        {
            return (originalString == null || originalString.Length <= maximumLength) ? originalString : originalString.Substring(0, maximumLength);
        }

Example use:

          string newString = oldString.Truncate(10);

Credit goes to this guy and one of the people in his comments: http://jamesfricker.blogspot.com.au/2007/08/truncating-string-in-c-easy-huh.html

Friday, January 11, 2013

OnClientClick breaks validation


PROBLEM: Your validators (RequiredFieldValidator, RangeValidator, RegularExpressionValidator etc) are not being called/fired when you have some client side javascript in OnClientClick that asks a yes/no question e.g. Are you sure you want to delete this?


<asp:Button ID="btnConfirmDelete"
                    runat="server"
                    Text="Delete this Session"
                    ValidationGroup="vgDelete"
                    onclick="btnConfirmDelete_Click"
                    OnClientClick='return confirm("Are you sure you want to delete this session?")' />


SOLUTION:
When the page is rendered, the javascript for the onclick will look something like:


onclick="return confirm('Are you sure?');WebForm_DoPostBackWithOptions(...)"

As you can see, the validation doesn't even have a chance to fire (which happens when WebForm_DoPostBackWithOptions is called).

(this guy figured that out: http://vaultofthoughts.net/OnClientClickBreaksValidation.aspx)

Changing it to the below fixes that:

'if (!confirm("Are you sure you want to delete this session?")) return false;'

BUT then you realise that the validators are being called AFTER the prompt (ideally you don't want to prompt the user that they're sure until the last minute after everything is completed). So the this version takes care of that:

'if(Page_ClientValidate()) return confirm("Are you sure you want to delete this session?"); return false;'

Some more info here: http://alvinzc.blogspot.com.au/2006/10/aspnet-requiredfieldvalidator.html

BUT if you're using validation groups, remember to specify it when you call Page_ClientValidate to prevent fields being validated that you don't want validated. Therefore the final version in our case is:

OnClientClick='if(Page_ClientValidate("vgDelete")) return confirm("Are you sure you want to delete this session?"); return false;'

http://techbrij.com/client-side-validation-using-asp-net-validator-controls-from-javascript
http://programmer.webhostingdevelopment.com/index.php/2010/03/specifying-validationgroup-in-page_clientvalidate-function/