Lier
Lier

Reputation: 308

validate a textbox that Doesn't Start or End With Special Character

I have some requirements that I need to implement a text box that doesn't allow special character at starting and ending of the string but it has option to allow in middle of the word example: 1)Some_@thing --True 2)_#2someThing --False 3)something_@ --false*

$(function () {
$('#text').on("change", function (e) {
if (this.value.match(/^[a-z0-9](?!.*?[^\na-z0-9]{100}).*?[a-z0-9]$/)) {
this.value = this.value.replace(/^[a-z0-9](?!.*?[^\na-z0-9]{100}).*?[a-z0-9]$/, '');
$("#eror").text("Accepts only Alphabets");
                   
                }   
         });

Upvotes: 0

Views: 715

Answers (2)

Matthew C. Lewis
Matthew C. Lewis

Reputation: 1

It looks like you may be looking for the reverse of what yash posted, screening for instances that break the rule, rather than conform to it.

Your 'if' conditional appears to be looking for a result that returns true if the special-character rule has been broken, so you would probably want something along the lines of:

//allows only letters and numbers at the start and end
/^[\W_\s].*$|^.*[\W_\s]$/

//allows only letters (and not numbers) at the start and end
/^[^A-Za-z_\s].*$|^.*[^A-Za-z_\s]$/

Both will allow special characters within the string itself, outside of the starting and ending characters, without triggering your boolean, but will trigger it if the strings starts or ends with those same characters.

As a side note, if you are only interested in testing for a regex match, and not with actually returning the regex matches, you should use:

regex.test('string')

//instead of
string.match(/regex/)

match is overkill for your needs here and will only slow down your application. test returns its result directly in boolean form and does so much quicker than match.

MDN Section on using 'test' (if you are interested in learning more about this specific use case)

Upvotes: 0

yash
yash

Reputation: 2271

Try pattern something like this ^[a-z0-9](?!.*?[^\na-z0-9]{100}).*?[a-z0-9]$

Here is the Demo of it. you can check it.

There's some error in your code too, here i had created one new fiddle. according to that you can modify your code. and it may work.

1> change your function to .change as i used in fiddle
2> compare pattern to string such like pattern.test(string).

New Fiddle with Working Pattern.
hope so above solution work for you.

Upvotes: 2

Related Questions