Saturday, July 18, 2015

How to validate text in javascript to prevent unwanted formatted text

   because malform text can be cause of web application failure. The malform string has purpose for Cross site scripting(XSS), SQL injection or any penetration purpose. So text input must be validated before it submitted to server.
   The following validation fuction is apply regular expression and yot can prefer to allow number, space, or any punctation : 

 function validateText(value,isAllowNumber,isAllowSpace,isAllowPunctation){  
   var regEx1 = /[A-Za-z\u0000-\uFFFF ]+/;  
   var isMatchRegex1 = regEx1.test(value); // check has readable character  
   var regex2 = /^(^([^0-9]*)$)/;  
   var isMatchRegex2 = !isAllowNumber ? regex2.test(value) : true; // check has readable number  
   var regex3 = /^(^([^ \t\r\n\v\f]*)$)/;  
   var isMatchRegex3 = !isAllowSpace ? regex3.test(value) : true; // check has space character  
   var regex4 = /^(^([^\x00-\x1F\x7F]*)$)/;  
   var isMatchRegex4 = regex4.test(value); // check has any control character  
   var regex5 =/^(^([^\\[\]!"#$%&'()*+,.:;<=>?@\/\^_`{|}~-]*)$)/; 
   var isMatchRegex5 = !isAllowPunctation ? regex5.test(value) : true;     // check has any punctation such as !@#$%^  
   var isValidValue = isMatchRegex1 && isMatchRegex2 && isMatchRegex3 && isMatchRegex4 && isMatchRegex5;  
   return isValidValue;  
 }  


Let's enjoy this function.

No comments:

Post a Comment