Validating an expression for "no spaces"

I tried:

self.username = ko.observable(data.username || null)
    .extend({ required: true, maxLength: 50 })
    .extend({ pattern: { message: 'Username cannot contain spaces.', params: '^\S*$' } });

and

self.username = ko.observable(data.username || null)
    .extend({ required: true, maxLength: 50 })
    .extend({ pattern: { message: 'Username cannot contain spaces.', params: '[\S]' } });

but a validation error is flagged even with the value "a".

The expression '^\S*$'seems to work with online JavaScript on-line JavaScript testers. I'm not sure why its flag.

+4
source share
2 answers

When using a string to define a regular expression, you need to avoid any backslashes, so it should be:

self.username = ko.observable(data.username || null)
   .extend({ required: true, maxLength: 50 })
   .extend({ pattern: { message: 'Username cannot contain spaces.', params: '^\\S*$' } });

If you use a regular expression literal instead of a string, you don't need to hide the backslash:

self.username = ko.observable(data.username || null)
   .extend({ required: true, maxLength: 50 })
   .extend({ pattern: { message: 'Username cannot contain spaces.', params: /^\S*$/ } });
+4
source

I assume you are using ko.validation?

If the regex fix doesn't work, you can try something like this (untested) ...

ko.validation.rules['doesntContain'] = {
    validator: function (val, checkFor) {
        return val.indexOf(checkFor) === -1;
    },
    message: 'The field must not contain [{0}]'
};
ko.validation.registerExtenders();


var myCustomObj = ko.observable(data.username || null).extend({ doesntContain: " " });
0
source

Source: https://habr.com/ru/post/1598470/


All Articles