Showing posts with label Phone number formatting. Show all posts
Showing posts with label Phone number formatting. Show all posts

Monday, October 24, 2016

KeyPress Methods in MS CRM 2016

In MS CRM 2016, now we can add KeyPress methods for text or number fields. 
KeyPress Events will help for validation of data or for formatting fields. 

With KeyPress methods you can easily restrict any text attribute to accept only numbers or only alphabets or format phone numbers. 

There are three KeyPress methods 

  • addOnKeyPress - using this method you can add event handler function, which will be called when keyPressed in text or number field. 
  • removeOnKeyPress - removes event handler for text or number field which added using addOnKeyPress. 
  • fireOnKeyPress - you can manually fire an event handler you created for text or number field. 
Here are some examples 

1. Format Phone number
  

contactScript =
{
    onLoadEvents: function () {
        Xrm.Page.getControl('telephone1').addOnKeyPress(contactScript.formattPhoneNumber);
    },
    formattPhoneNumber: function () {
        var phoneNo = Xrm.Page.getControl("telephone1").getValue();
        if (phoneNo.length == 10) {
            var formattedPhone = phoneNo.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
            Xrm.Page.getAttribute('telephone1').setValue(formattedPhone);
        }
    },
};


Call contactScript.onLoadEvents on Form Load, Once number started entering into phone number(telephone1) attribute,  formattPhoneNumber is triggering , once phone number length reaches 10, it will format phone number to 123-456-0010 format. For format phone number you can use any other regular expression. 

2. Restrict only numbers

In above example (format Phone number), user will able to enter alphabets also, but mostly phone number contains only numbers. so to restrict only numbers you can change formattPhoneNumber function as 

formattPhoneNumber: function () {      
        var phoneNo = Xrm.Page.getControl("telephone1").getValue();
        phoneNo = phoneNo.replace(/\D/g, '');
        Xrm.Page.getAttribute('telephone1').setValue(phoneNo);
        if (phoneNo.length == 10) {
            var formattedPhone = phoneNo.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
            Xrm.Page.getAttribute('telephone1').setValue(formattedPhone);
        }
    },

3. Restrict only Alphabets

contactScript =
{
    onLoadEvents: function () {
          Xrm.Page.getControl('jobtitle').addOnKeyPress(contactScript.OnlyAlphabets);
      
    },

    OnlyAlphabets: function () {
        var firstName = Xrm.Page.getControl("jobtitle").getValue();
        firstName = firstName.replace(/[^a-z]/gi, '');
        Xrm.Page.getAttribute('jobtitle').setValue(firstName);
    }
};

4. Suggest Accounts name based on Existing leads 

This is autocomplete example, which will show lead names when user enters at least 3 characters in account name. In this example retrieving data from lead entity synchronously, and retrieving only 10 leads at a time.

Here is complete code

var AccountScript = {
    onLoadEvents: function () {
        Xrm.Page.getControl("name").addOnKeyPress(AccountScript.keyPressFcn);
    },
    keyPressFcn: function (evt) {
        try {
            var userInput = Xrm.Page.getControl("name").getValue();

            /*Search in Lead will be started when user enters atleast 3 characters*/
            if (userInput.length >= 3) {
                resultSet = {
                    results: new Array(),
                };

                var userInputLowerCase = userInput.toLowerCase();

                /*Retrieve Leads whose full name begins with name entered by user.
                Retrieving only 10 Leads and autocomplete will be shown when user enters minimum 3 characters. */

                var req = new XMLHttpRequest();
                req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/leads?$select=fullname&$filter=startswith(fullname,'" + userInputLowerCase + "')&$orderby=fullname asc", false);
                req.setRequestHeader("OData-MaxVersion", "4.0");
                req.setRequestHeader("OData-Version", "4.0");
                req.setRequestHeader("Accept", "application/json");
                req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                req.setRequestHeader("Prefer", "odata.maxpagesize=25");
                req.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        req.onreadystatechange = null;
                        if (this.status === 200) {
                            var leadresults = JSON.parse(this.response);
                            for (var i = 0; i < leadresults.value.length; i++) {
                                var fullname = leadresults.value[i]["fullname"];

                                /*Add found lead in array which will be shown in autocomplete window*/
                                resultSet.results.push({
                                    id: i,
                                    fields: [fullname]
                                });
                            }
                        }
                        else {
                            alert(this.statusText);
                        }
                    }
                };
                req.send();
               
                /*If at least one record found then only show autocomplete window.*/
                if (resultSet.results.length > 0) {
                    evt.getEventSource().showAutoComplete(resultSet);
                } else {
                    evt.getEventSource().hideAutoComplete();
                }
            }
        } catch (e) {
          
            alert(this.statusText);
        }
    }
};


call  AccountScript.onLoadEvents function on Account form load event. 



Wednesday, June 11, 2014

Mask Phone number, Date fields in CRM

NOTE: THIS IS UNSUPPORTED CRM 2013 CUSTOMIZATION.

For Complete code check https://maskedinputcrm2013.codeplex.com

To provide masking for input fields in CRM form we can use jQuery masked input plugin.
 Using this plugin we can easily add masking for not only phone number, fax, date fields but also we can add masking for like SSN number, driving license number etc.
Also when adding this masking, this plugin is already taking care of inputs validation like phone number should contain only numbers.
 We can add our own formats also using this plugin. For more details about this plugin, Check  http://digitalbush.com/projects/masked-input-plugin/
For CRM implementation
·         Download minified masked input plugin file from https://raw.github.com/digitalBush/jquery.maskedinput/1.3.1/dist/jquery.maskedinput.min.js
·         Add this JS file to CRM web resources.
·         Create new JavaScript web resource and add following code in that file
var CustomMaskScript = {
    MaskInputField: function (fieldName, format) {       
        var control = Xrm.Page.getControl(fieldName);
        if (control != null && control.getControlType() == 'standard') {
            control.setFocus();
            if (Xrm.Page.getAttribute(fieldName).getAttributeType() == 'datetime') {
                var input = $("#" + fieldName + "_i").find("input");
                if (input != null)
                    input.mask(format);
            } else
                $("#" + fieldName + "_i").mask(format);
        }
    },
};


·         Now add both file in entity form library where you want to use masking

  •   Call MaskInputField function on load of Form with attribute name and Format as parameters.

'new_birthdate','99/99/9999'
·         Save and publish customization.
·         And maked input is ready to use

Above example is for manual masking for fields which we can to add masking.

If by default we want to add masking for all phones and date attributes on Form then use following script

var DefaultMask = {
    MASK_date: '99/99/9999',
    MASK_Phone: '(999) 999-9999',

    MaskDatePhoneInput: function () {
        var PageAttributes = Xrm.Page.data.entity.attributes.get();
        var fieldName = '';
        var Format = '';
        for (var i in PageAttributes) {
            var control = PageAttributes[i].controls.get(0);
            fieldName = PageAttributes[i].getName();
            Format = PageAttributes[i].getFormat();
            if (Format == 'phone' || Format == 'date') {
                control.setFocus();
                if (PageAttributes[i].getAttributeType() == 'datetime') {
                    var input = $("#" + fieldName + "_i").find("input");
                    if (input != null)
                        input.mask(ContactDefaultMask.MASK_date);
                } else
                    $("#" + fieldName + "_i").mask(ContactDefaultMask.MASK_Phone);
            }
        }
    },
}
Add this in JS web resources and call function on load.  This will add masking for all phone number and date fields on Form.

Here are some examples of masking 
·         Date
Without Mask:

With Mask

Mask Format:  99/99/9999

·         Phone number
Without Mask:


With Mask


Mask Format:  (999) 999-9999

·         Phone number with Extension
Without Mask:


With Mask


Mask Format:  (999) 999-9999? X99999

·         Social Security Number
Without Mask:


With Mask


Mask Format:  999-99-9999

·         Custom (e.g. Wisconsin Driving license)
Without Mask:


With Mask


Mask Format:  a-9999999999


For Complete code check https://maskedinputcrm2013.codeplex.com