Friday, March 30, 2012

Numeric Only Text Field With Leading Zeros

The requirement is a field that allows only numeric values but can also start with a zero. A standard integer (Type = Whole Number) field won’t accomplish this because it will drop the leading zeros. A text (Type = Single Line of Text) field won’t do it alone as it will not constrain your input to only numbers, but we can add a little JavaScript to make everything work.
In this example we’ll set the Maximum Length on our new field to 8. Using JavaScript we’ll limit the typed input to numbers and add leading zeros if the entered number is less than 8 characters in length.
//Control = Form - Event = OnLoad 
//Also check Pass execution context as first parameter
function OnLoad() {
    document.getElementById("new_field").attachEvent("onkeypress", KeyPress);
}

//Control = new_field - Event = OnChange
function Field_OnChange() {
    Xrm.Page.getAttribute("new_field").setValue(
     Xrm.Page.getAttribute("new_field").getValue()
        .replace(/[^0-9]/g, ''));
    while (Xrm.Page.getAttribute("new_field").getValue().length < 8) {
        Xrm.Page.getAttribute("new_field").setValue('0' + 
         Xrm.Page.getAttribute("new_field").getValue());
    }
}

function KeyPress(e) {
    var charCode = (e.which) ? e.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
Edit: Andrii pointed out that a copy and paste would still allow non-numeric characters so I've updated to strip those characters out during the OnChange event.