Search code examples
javascriptdynamics-crm-2016

JavaScript Cannot read property 'preventDefault' of null


I am checking the phoneNumber.length in my CRM form. So far I got the check between 8-15 character = acceptable to work. When I try to stack an 'if' to check for zero characters I get: TypeError: Cannot read property 'preventDefault' of null at checkPhoneNumber

function checkPhoneNumber(executioncontext) {
    var phoneNumber;
    phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();

    if (phoneNumber == null) {
        Xrm.Page.ui.setFormNotification("Phonenumber can't be empty", "WARNING", "telephone1nc1");
        Xrm.Page.getControl("telephone1").setFocus(true);
        executioncontext.getEventArgs().preventDefault();
    } else {
        Xrm.Page.ui.clearFormNotification("telephone1nc1");
        //Insert 8-15 characters
        if (phoneNumber != null) {

            if (phoneNumber.length < 8 || phoneNumber.length > 15) {
                Xrm.Page.ui.setFormNotification("Phonenumber must be between 8-15 chars..", "ERROR", "telephoneerror1");
                Xrm.Page.getControl("telephone1").setFocus(true);
            } else {
                if (phoneNumber == null) {
                    Xrm.Page.ui.setFormNotification("Telefonnummret får inte vara tomt", "WARNING", "telephone1nc1");
                    Xrm.Page.getControl("telephone1").setFocus(true);
                    //executioncontext.getEventArgs().preventDefault(); //vid 0 bombar scriptet
                } else {

                    Xrm.Page.ui.clearFormNotification("telephone1nc1");
                }
                Xrm.Page.ui.clearFormNotification("telephoneerror1");

            }
            /*var regex = /^\+(?:[0-9] ?){6,14}[0-9]$/;

            if (regex.test(executionObj)) {
                // Valid international phone number
            } else {
                // Invalid international phone number */
        }
    }
}

Once I get that sorted out I will start working on the code to check for international format and inserting the country code based on country of the entity. Hence the commented var regex.


Solution

  • You need to ensure executioncontext.getEventArgs() is not null.

    Easiest way to do this in a single line:

    executioncontext.getEventArgs() && executioncontext.getEventArgs().preventDefault();