Search code examples
javascriptangularjsvalidationangular-xeditable

Angular Xeditable - can't get correct value for validation using onbeforesave event


I am trying to add validation logic to the editing of message format values we use. I have created plunker here to show the issue. Here is the code for the curly brace validation.

vm.formatCheck = function (resource) {

console.log(resource.Value);

if (resource.Value.indexOf('{') > -1 || resource.Value.indexOf('}') > -1) {

    var x = resource.Value.split('{').length - 1;
    var y = resource.Value.split('}').length - 1;

    if ((x + y) % 2 === 1) {
        alert("Incorrect Message format");
        return;
    }

  }
};

Example: If you edit the first value ({JobRole} for {Organisation}) and remove the trailing curly brace ({JobRole} for {Organisation)

The alert("Incorrect Message format"); never shows because it gets the original value - {JobRole} for {Organisation} and not {JobRole} for {Organisation

If I move the validation logic to the onaftersave event I get the correct value and validation fires, but it will show/save the incorrect value, which I do not want. So how can I get around this? Any help appreciated.

  • Not sure if I could use defer, promise to resolve this - but not sure if even possible with Angular Xeditable?

Solution

  • Here is my plunker with it working: Plunker

    Basically, I changed your html to this:

    <a href="#" e-name="resource" editable-textarea="res.Value" e-rows="5" e-cols="30"
                       onbeforesave="vm.formatCheck($data)"
                       onaftersave="vm.onGridItemChanged(res)">{{ res.Value || 'empty' }}</a></a>
    

    I'm passing $data instead of the 'res'. $data is the value of the object property you are actually changing.

    And in the controller, your validation function. 'Resource' is now the $data which contains the value of your property you are trying to change. So you check it, and you return an error message. If you don't want a error message to show up next to the field return "";

    vm.formatCheck = function (resource) {
    
            console.log(resource);
    
            if (resource.indexOf('{') > -1 || resource.indexOf('}') > -1) {
    
                var x = resource.split('{').length - 1;
                var y = resource.split('}').length - 1;
    
                if ((x + y) % 2 === 1) {
                    alert("Incorrect Message format");
                    return "Incorrect Message format";
                }
    
            }
        };