javascript - Weird regex issue -


i using javascript validate pattern , i'm looking allow alphanumeric values , punctuations. strangely, when enter ( or ) followed fails if give space works. doing wrong?

$(document).on('blur', '#comment', function () {       var rgx = /[a-za-z0-9 _.,!"']$/;       var value = $(this).val();       if (!rgx.test(value) == true){           $("#comment").focus();           $("#commenterror").val("please use alphabets, numbers , punctuations");       }else{         $("#commenterror").val("");       }   }); 

test cases:

passes for

input: ( 

fails

input: (a 

your current pattern checking last character in string.

you need have pattern checks entire string. accomplished using ^ , $ anchors , using 1 or more quantifier * (assuming commenting optional).

your regex pattern can be:

/^[\w .,!"']*$/ or /^[a-z0-9 _.,!"']*$/i or /^[u20-u22u27u2cu2eu30-u39u41-u5au5f]*$/i

the first brief (my preference), second readable, , third using unicode , hardest comprehend. fast, speed isn't criteria.

here jsfiddle demo refinements , commented advice.

html:

<input id="comment" name="comment" value="( a"> <i> press tab trigger validation</i><br> <input id="commenterror" value="comment limit: 25. use letters, numbers, ,  punctuation.">  <!-- have added "?" regex pattern because seems permissible. --> <!-- invalid values: "(a", "( a", "12345678901234567890123456" --> <!-- valid values: "", "hello world", "l0ts, "of go.od' st_uff!?" -->  <!-- additional advice: if storing input value in database table,      should limit field length table column can hold.      if, per se, saving varchar(255), set #comment field limit      255 value isn't truncated during saving. --> 

css:

#comment{     width:200px; } #commenterror{     display:none;     width:400px; } 

js:

$(document).on('blur','#comment',function(){     // no variable declaration needed     if(/^[\w .,!"'?]{0,25}$/.test($(this).val())){  // contains valid chars w/ limit         $("#commenterror").hide();     }else{         $("#comment").focus();  // disallows focus on other field         $("#commenterror").show();     } }); 

Comments