0

How to write a regular expression for a text field which accepts all characters except a comma (,) and do not accept a white space at both the ends? I have tried

[^,][\B ] 

but no use

like 'product generic no' instead of 'product,generic,no' or ' product generic no '

stema
  • 90,351
  • 20
  • 107
  • 135
rajesh4ext
  • 5
  • 1
  • 4

3 Answers3

0

Using a Perl regular expression

/^\S[^,]*\S$/

This should work from 2 characters up, but fails in the edge case where the string has only one non-comma character. To cover that too:

/^((\S[^,]*\S)|([^\s,]))$/
SzG
  • 12,333
  • 4
  • 28
  • 41
0

Something like below:

/^\S[^,]*\S$/
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

I suggest a solution without regular expression. As you said you're using JS so the function is in JavaScript:

function isItInvalid(str) {
    var last = str.length - 1;
    return (last < 2 || 
            str[0] == ' ' ||
            str[last] == ' ' ||
            str.indexOf(',') != -1);
}

EDIT: Just made it a bit more readable. It also checks if the string is at least 3 chars.

core1024
  • 1,882
  • 15
  • 22
  • by using this we can display error msg after entering data ..but i want to restrict while entering – rajesh4ext Feb 27 '14 at 08:26
  • Just instead of `regex` use the `validator` option ;) See how here http://stackoverflow.com/questions/5186595/extjs-dependent-field-validation – core1024 Feb 27 '14 at 08:34
  • this worked but i am unable to restrict to not to enter :( validator: function(value){ var last = value.length - 1; if((value[0] == ' ' ||value[last] == ' ' )){ return 'Space not Allowed at start and end'; } if(value.indexOf(',') != -1) { return ', not allowed'; }else { return true; } } – rajesh4ext Feb 27 '14 at 09:36
  • You can use `maskRe` to restrict the comma like that `maskRe: /[^,]/,`. This works per character (i think) so don't try to filter the space. – core1024 Feb 27 '14 at 11:51