0

Have some error in this, can you guys please tell me what i am doing wrong

function verifyGroup(groupVal, errorid) { groupVal = $.trim(groupVal); if (groupVal != '') { var splChars = "*|,\":<>[]{}`\';()@&$#%!+-"; for (var i = 0; i < groupVal.length; i++) { console.log(groupVal.charAt(i)+' == '+splChars.indexOf(groupVal.charAt(i))); if (splChars.indexOf(groupVal.charAt(i)) != -1) { $("#" + errorid).addClass("form-error").html("Illegal characters detected!"); return false; } else { $("#" + errorid).removeClass("form-error").html(""); return true; } } } else { $("#" + errorid).addClass("form-error").html("Group name should not be empty"); return false; } } 

DEMO

2 Answers 2

1

Use a regex

function verifyGroup(groupVal, errorid) { groupVal = $.trim(groupVal); console.log(groupVal); console.log(errorid); if (groupVal != '') { var regex = /[*|,\\":<>\[\]{}`';()@&$#%!+-]/; if(regex.test(groupVal)){ $("#" + errorid).addClass("form-error").html("Illegal characters detected!"); return false; } else { $("#" + errorid).removeClass("form-error").html("valid"); return true; } } else { $("#" + errorid).addClass("form-error").html("Group name should not be empty"); return false; } } $(function() { // Handler for .ready() called. $('#submit').click(function(){ verifyGroup($('#ipId_create').val(), 'error_id'); }); }); 

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

hey dude, thank you very much, it works well, But want to know, 1. what was my mistake, as indexOF should work. 2. IS .test(), will be always good for this kind of validation.
@SAM it was because of the return true in the else portion of the index condition. see jsfiddle.net/arunpjohny/fAywy/3 the problem is if the first character is not a special character you where not continuing the tests... it was just returning true
0

The comparison to -1 should be == not !=.

1 Comment

this should be a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.