Friday 28 November 2014

Find Invalid chars from a given string using JavaScript

 

// Test Data
var testString1 = "Te<s'ting";
var testString2 = "Test";

// set of Invalid characters.These should be avoided from test  strings
var RegExp = /[\'\<\>\"\%\;\(\)\&\+\#\*\--]/i;

// 1st Test String

// If the test string contains invalid characters then
if (RegExp.test(testString1)) {
    // Found a match with Invalid chars
    alert(testString1 + ' contains invalid chars');
}
else {
    // Not matching with Invalid chars
    alert('No invalid chars in ' + testString1);
}

// 2nd Test String

if (RegExp.test(testString2)) {
    // Found a match with Invalid chars
    alert(testString2 + ' contains invalid chars');
}
else {
   // Not matching with Invalid chars
    alert('No invalid chars in '+ testString2);
}