web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Field validation using Javascript

(0) ShareShare
ReportReport
Posted on by

Hello,

The CRM environment of my organization send a XML file to the Department of State almost everyday with several of records, the DOS has a few requirements for fields and there are characters that are not allowed. Initially I was using this code to validate these fields

function ValidateSpecialChar()

{

var Regexp=/[^a-zA-Z0-9 ]/;  //this will allow space

var value=Xrm.Page.getAttribute("name").getValue();

if (Regexp.test(value)) {

 alert("Special Character is Not Allowed !!");

 Xrm.Page.getAttribute("name").setValue(null);

 }

else {

   return false;

 }

}

 

However there are fields that do allow some characters:

  1. The contacts first and last name must be alphabets ([A-Z][a-z])
  2. The account names can have 8 special characters such as & , ', ",  #, -, /, <, >
  3. The city name must be alphabets ([A-Z][a-z])
  4. The phone number attribute can have only  0-9, -, (,) characters as a valid characters
  5. The postal code attribute can have only 0-9, - characters as a valid characters

 Would anyone be able to help me achieve this with Javascript? I can compensate you for time and effort.

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hey Lucas,

    Using "alert" in your client script is not supported and will break your forms in the future.
    For field validation in particular it is recommended that you use the "setNotification" method on controls. This adds a red X 
    dynamicscommunity_5F00_attributenotification.png

    Docs: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/controls/setnotification

    I had to take some liberties in assuming which fields you need exactly but, they can easily be adjusted.

    1. The contacts first and last name must be alphabets ([A-Z][a-z])

    function validateLastName(executionContext) {
       var formContext = typeof executionContext != 'undefined' ? executionContext.getFormContext() : Xrm.Page; // get formContext
       
       var pattern = /[^a-z]/ig;
    var fieldName = 'lastname'; var currentValue = formContext.getAttribute('lastname').getValue(); if (pattern.test(currentValue)) { formContext.getControl(fieldName).setNotification('Invalid value, please only enter letters.'); } else { formContext.getControl(fieldName).clearNotification(); } }

    2. The account names can have 8 special characters such as & , ', ",  #, -, /, <, >

    function validateAccountName(executionContext) {
       var formContext = typeof executionContext != 'undefined' ? executionContext.getFormContext() : Xrm.Page; // get formContext
       
       var pattern = /[^a-z0-9&\'"#\-\/<>]/ig;
    var fieldName = 'name'; var currentValue = formContext.getAttribute(fieldName).getValue(); if (pattern.test(currentValue)) { formContext.getControl(fieldName).setNotification('Invalid value, only these special characters are allowed: &\'" #-/<>'); } else { formContext.getControl(fieldName).clearNotification(); } }

    3. The city name must be alphabets ([A-Z][a-z])

    function validateCity1(executionContext) {
       var formContext = typeof executionContext != 'undefined' ? executionContext.getFormContext() : Xrm.Page; // get formContext
       
       var pattern = /[^a-z]/ig;
    var fieldName = 'address1_city'; var currentValue = formContext.getAttribute(fieldName).getValue(); if (pattern.test(currentValue)) { formContext.getControl(fieldName).setNotification('Invalid value, please enter only letters.'); } else { formContext.getControl(fieldName).clearNotification(); } }

    4. The phone number attribute can have only  0-9, -, (,) characters as a valid characters

    function validateTelephone1(executionContext) {
       var formContext = executionContext ? executionContext.getFormContext() : Xrm.Page; // get formContext
       
       var pattern = /[^0-9,\-]/ig;
    var fieldName = 'telephone1'; var currentValue = formContext.getAttribute(fieldName).getValue(); if (pattern.test(currentValue)) { formContext.getControl(fieldName).setNotification('Invalid value, please enter only numbers or - and ,'); } else { formContext.getControl(fieldName).clearNotification(); }
    }

    5. The postal code attribute can have only 0-9, - characters as a valid characters

    function validatePostalCode(executionContext) {
       var formContext = typeof executionContext != 'undefined' ? executionContext.getFormContext() : Xrm.Page; // get formContext
       var pattern = /[^0-9\-]/ig;
    var fieldName = 'address1_postalcode'; var currentValue = formContext.getAttribute(fieldName).getValue(); if (pattern.test(currentValue)) { formContext.getControl(fieldName).setNotification('Invalid value, please enter only numbers or -'); } else { formContext.getControl(fieldName).clearNotification(); }
    }

    The "new RegExp" constructor in your script is also not necessary, just starting a string variable assignment with / will trigger javascript to assume a regular expression.

    The variable formContext you see at the start of every line is taking into account the deprecation for Xrm.Page in version 9.
    From version 9 onward getFormContext should be used, instead of Xrm.Page - this of course only works if you pass the execution context on your calling of the events.

    Also a quick tip: To validate/test regular expressions I always use https://regex101.com/ 

    --

    If you have any other questions or are having issues with these scripts, please let me know.
    If you found my answer helpful, please mark it as such/verified :-)

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi Lucas,

    Michel is correct , you should go the way Michel suggested. I have done little modification to reduce the redundancy of the code. Just created one reusable method where you need to  pass the validation details. Hope this helps.

    function ValidateField()
    {
        //1. The contacts first and last name must be alphabets ([A-Z][a-z])
        var _expression = /[^a-z]/ig;
        //2. The account names can have 8 special characters such as & , ', ",  #, -, /, <, >    
        _expression = /[^a-z0-9&\'"#\-\/<>]/ig;
        //3. The city name must be alphabets ([A-Z][a-z])
        _expression = /[^a-z]/ig;
        //4.  phone number attribute can have only  0-9, -, (,) characters as a valid characters     
        _expression = /[^0-9,\-]/ig;
        //5. The postal code attribute can have only 0-9, - characters as a valid characters
        _expression = /[^0-9\-]/ig;_
        var _fieldName = 'lastname';
    
        var _messages = 'Invalid value, please only enter letters';
        validateFieldUtility(_fieldName, _expression,_messages);
    }
    
    function validateFieldUtility(_fieldName, _expression,_messages) {  
        var currentValue = Xrm.Page.getAttribute(_fieldName).getValue();
        if (_expression.test(currentValue)) {
            Xrm.Page.getControl(_fieldName).setNotification(_messages);
        } else {
            Xrm.Page.getControl(_fieldName).clearNotification();
        } 
    }
  • Community Member Profile Picture
    on at

    Thank you so much for sharing the code. However I am facing a this script error:

    TypeError: Cannot read property 'setNotification' of null

       at validateLastName (ats.dev.allianceabroad.com/.../aag_ValidateLastName)

       at eval (eval at RunHandlerInternal (ats.dev.allianceabroad.com/.../ClientApiWrapper.aspx), <anonymous>:1:1)

       at RunHandlerInternal (ats.dev.allianceabroad.com/.../ClientApiWrapper.aspx)

       at RunHandlers (ats.dev.allianceabroad.com/.../ClientApiWrapper.aspx)

       at ExecuteHandler (ats.dev.allianceabroad.com/.../ClientApiWrapper.aspx)

       at Mscrm.TurboForm.Control.CustomScriptsManager.$C7_1 (ats.dev.allianceabroad.com/.../JsProvider.ashx;ids=1223231347-405283869:8908:91)

       at Mscrm.TurboForm.Control.CustomScriptsManager.executeHandler (ats.dev.allianceabroad.com/.../JsProvider.ashx;ids=1223231347-405283869:8854:18)

       at Mscrm.TurboForm.Control.CustomScriptsManager.executeHandlerByDescriptor (ats.dev.allianceabroad.com/.../JsProvider.ashx;ids=1223231347-405283869:8885:18)

       at ats.dev.allianceabroad.com/.../JsProvider.ashx;ids=1223231347-405283869:8893:19

       at ats.dev.allianceabroad.com/.../global.ashx

    Do I have to change the method to Xrm.Page and setFormNotification?

  • Michel van den Brink Profile Picture
    4,697 on at

    Hey Lucas,

    If you are getting that error message when using my script example, that looks like it can't find the 'lastname' field. Are you running that script on the Contact form and do you have it set to the OnChange event of the lastname field?

    If the lastname field isn't on the form, or if you are trying to run that script on a different entity (one without lastname) it would give you that error.

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Hi Lucas,

    setNotification is used for field level notifications, so that is fine.

    Can you check in debugger window the values of field name and the message?

    I think one of them is not populated.

  • Community Member Profile Picture
    on at

    I am actually using the Full Name composite, would the validation work with that?

  • Community Member Profile Picture
    on at

    I have modified the code to use with First Name and Last Name field. This is how the code is:

    function validateFirstName(executionContext) {
    var formContext = typeof executionContext != 'undefined' ? executionContext.getFormContext() : Xrm.Page; // get formContext

    var pattern = /[^a-z]/ig;
    var fieldName = 'firstname';
    var currentValue = formContext.getAttribute(fieldName).getValue();
    if (pattern.test(currentValue)) {
    formContext.getControl(fieldName).setNotification('Invalid value, please only enter letters.');
    } else {
    formContext.getControl(fieldName).clearNotification();
    }

    }

    And the screenshots show how it has been setup and the script error:

    Validation.jpg

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Can you please check the value of formContext before the var pattern line?

    Xrm.Page.getControl(fieldName).setNotification(message) and

    formContext.getControl(fieldName).setNotification(message) are correct syntax for this.

  • Suggested answer
    Alex Fun Wei Jie Profile Picture
    33,628 on at

    Hi,

    you should use

    Xrm.Page.getControl(fieldName).setNotification('Invalid value, please only enter letters.');

    Xrm.Page.getControl(fieldName).clearNotification();

    msdn.microsoft.com/.../gg334266.aspx

    The method that you use only working in CRM online and V9.0, but you are using CRM 2016

    docs.microsoft.com/.../setnotification

    remove all the code related to executioncontext and use back the Xrm method

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Yes, just noticed.

    Wei is right.

    If you are on CRM 2016 you need to use:

    Xrm.Page.getControl(fieldName).setNotification('Invalid value, please only enter letters.');

    Good catch

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans