security.js 1.2 KB
/**
 * 校验input, 防止SQL注入
 * @author: 赵彪<bill.zhao@yoho.cn>
 * @date: 2015/11/30
 */

var $ = require('jquery'),
    tip = require('./tip');

/**
 * hasStrangeInput() return true when input have danger value
 *
 * @param {Bool} needConvert Set if the danger input value should be converted to space
 * @return {Bool} true/false If the input have danger value
 */
function hasDangerInput(needConvert) {
    var validationPartten = /['"<>&\|]|--/g,
        inputs = $('input[type!=hidden], textarea'),
        inputsLength = inputs.length;

    // to set if the input value should be coverted, and its default value is true;
    var willConvert = needConvert === undefined || typeof needConvert !== 'boolean' ? true : needConvert ;

    for (var i = 0; i < inputsLength; i++) {
      var val = inputs.eq(i).val();
      if (validationPartten.test(val)) {
        if (willConvert) {
          inputs.eq(i).val(val.replace(validationPartten, ' '));
        } else{
          var matchChars = val.match(validationPartten).join(' ');
          tip.show('不可以输入 ' + matchChars + ' 哦!');
        }
        return !willConvert && true;
      }
    }

  return false;
}


exports.hasDangerInput = hasDangerInput;