Articles in this section
Category / Section

How to apply dynamic custom validation message in grid using angular JS

1 min read

We can apply a custom validation message for the grid dynamically using JQuery validator in AngularJS.

Solution:

JS:

Grid rendering code:

<body ng-controller="PhoneListCtrl">
  <div class="cols-sample-area">
                <div id="Grid" ej-grid e-datasource="data e-editsettings-allowadding="true" e-toolbarsettings-showtoolbar="true" e-toolbarsettings-toolbaritems="tools" e-allowpaging="true" e-columns ="columns"/>
  </div>

 

Define custom validation method “customCompares” for the column:

In the below code example we have called the custom validation method for the column “EmployeeID” with the parameter “params” (1, 10,”EmployeeID”) values.

 
angular.module('listCtrl', ['ejangular'])
        .controller('PhoneListCtrl', function ($scope) {
$scope.data = null;
            $scope.tools = ["add", "edit", "delete", "update", "cancel"];
            $scope.columns = [
 
                 { field: "EmployeeID", headerText: "EmployeeID", validationRules: { customCompares: [1, 10, "EmployeeID"], required: true } },
 
                 { field: "LastName", headerText: "LastName" },
 
                 { field: "FirstName", headerText: "FirstName", editType: ej.Grid.EditingType.Numeric },
 
                 { field: "Title", headerText: "Title"},
 
            ];
        });

 

Defining error message for the custom validation

Initially the custom validation message was declared as “null”.

So while changing the custom validation message dynamically, then we need to overwrite the default validation message with custom validation message using “messages” property of the JQuery validator.

angular.module('listCtrl', ['ejangular'])
        .controller('PhoneListCtrl', function ($scope) {
//Initialize the custom validation message
            var errorMessage =null;
 
            $scope.setError = function (errorValue) {
                errorMessage = errorValue;
                //Overwriting the default message with custom validation message
                $.validator.messages.customCompares = errorValue;
 
            }
            $.validator.addMethod("customCompares", function (value, element, params) {
 
                if (element.value.length > params[0] && element.value.length < params[1]) {
 
                    return true;
 
                } else {
 
                    var errorTexts = params[2] + " is mandatory and must be between 1 and 10 characters.";
//Dynamically set the validation message
                    $scope.setError(errorTexts);
                   
                    return false;
 
                }
          
            }, errorMessage);

 

Result:

Figure: Applied custom validation message

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied