0
votes

I have created within knockoutJS a computed observable that supports user input as well as performs text manipulation on the input.

This observable is bound to input field and label. The intent is to allow a user to enter a new name but I want to prevent the user from using non-alphanumeric characters. The function works both in bindings and evaluation of the string, but the replace function does not seem to update. The substring function works (limiting the text to 255 characters) but I think I have something not set exactly right in the replace. Int eh current funciton, if an illegal character is entered the user receives the toastr alert but the replace function does not replace the character with white space. I'd appreciate any suggestions.

html

<label class="reportNameTextBox" title="Click to edit report name"  data-bind="text: NameFormatted() == null || NameFormatted().trim().length == 0 ? '[ Click To Enter Name ]' : NameFormatted(), css: { 'noData': NameFormatted() == null || NameFormatted().trim().length == 0 }"></label>
            <input class="editInput" type="text" data-bind="value: NameFormatted" />

knockout

report.NameFormatted = ko.computed({
     read: function () {
           return report.Name().substring(0, 255);
           },
     write: function (value) {
           var insertedText = value;
           var Exp = /^[a-zA-Z0-9]*$/i;
           if (!insertedText.match(Exp)) {
           DisplayWarning('Attention', 'Non-alphanumeric may not be used.');
                            return report.Name(insertedText.substring(0, 255)).replace(/[^a-zA-Z 0-9]+/g, ''); ;
           }
           else {
           DisplayWarning('Success', 'yeah');
           return report.Name(insertedText.substring(0, 255));
           }
          },
    owner: this
});
1
Do you not need to chain the .replace to the substring(0,255) bracket, rather than report.Name() - MDEV
Also note that that space in your character class is just a character like any other, so spaces will not be removed by the pattern. - Martin Ender
@SmokeyPHP That was it good eye! if you will resubmit that as an answer vs a comment I will mark it as the answer. Thanks - rlcrews
@rlcrews Good to know! No worries. Answer posted - MDEV

1 Answers

0
votes

I believe your problem lies on this line:

return report.Name(insertedText.substring(0, 255)).replace(/[^a-zA-Z 0-9]+/g, '');

You're chaining the replace method to the wrong object (report.Name instead of substring)

return report.Name(insertedText.substring(0, 255).replace(/[^a-zA-Z 0-9]+/g, ''));

Just move the replace method inside the bracket and it should work as expected.