Javascript 如何在表单的验证函数中忽略特定验证以禁用“提交”按钮

Javascript 如何在表单的验证函数中忽略特定验证以禁用“提交”按钮,javascript,Javascript,我有一个表单,其中有一个字段,当字符超过30个时,会显示一条警告消息。该警告是一种验证,用于警告用户特定情况不允许超过我正在使用的应用程序的30个字符。 我需要的是警告验证不应该像其他验证那样阻止提交按钮。因此,如果我们有警告消息,用户仍然可以提交。 我想知道我需要在验证函数中做什么样的更改 /* Listen on form submission and validate form */ $('.validate-form').on('click', function(event)

我有一个表单,其中有一个字段,当字符超过30个时,会显示一条警告消息。该警告是一种验证,用于警告用户特定情况不允许超过我正在使用的应用程序的30个字符。 我需要的是警告验证不应该像其他验证那样阻止提交按钮。因此,如果我们有警告消息,用户仍然可以提交。 我想知道我需要在验证函数中做什么样的更改

/* Listen on form submission and validate form
   */
  $('.validate-form').on('click', function(event) {
    event.preventDefault();
    var errors = cargoflux.validateForm();
    if (typeof errors === 'object') {
      var firstError = errors[0];
      var position   = firstError.topOffset - 50;

      $("html, body").animate({ scrollTop: position }, 'fast');
      return;
    }
    window.SubmitShipmentForm();
  });
警告信息:

function validateLength(value, options) {
    var warningLength = options.warningLength;
    var maxLength = options.maxLength;
    if (warningLength && value.length > warningLength && value.length <= maxLength) {
      throw 'Warning: current shipment does not allow to exceed ' + warningLength + ' characters';
    }else if(maxLength && value.length > maxLength) {
      throw 'Warning: current shipment does not allow to exceed ' + warningLength + ' characters <br> Field cannot exceed ' + maxLength + ' characters';
    }
  }
函数验证长度(值、选项){
var warningLength=options.warningLength;
var maxLength=options.maxLength;
if(warningLength&&value.length>warningLength&&value.length最大长度){
抛出“警告:当前装运不允许超过“+warningLength+”个字符
字段不能超过“+maxLength+”个字符; } }
验证JS:

$(function() {

  // Define namespace if non-existant
  if (typeof cargoflux === 'undefined') {
    cargoflux = new Object();
  }

  var Regex = {
    email: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
    phoneNumber: /^\+?\d+$/,
    timeHHMM: /^\d\d:\d\d$/
  };

  var Schema = {
    // sender
    'shipment[sender_attributes][company_name]': {
      maxLength: 50,
      required: true
    },
    'shipment[sender_attributes][attention]': {
      maxLength: 50,
      warningLength: 30,
      required: false
    },
    'shipment[sender_attributes][address_line1]': {
      maxLength: 30,
      required: true,
    },
    'shipment[sender_attributes][address_line2]': {
      maxLength: 30,
      required: false,
    },
    'shipment[sender_attributes][address_line3]': {
      maxLength: 30,
      required: false,
    },
    'shipment[sender_attributes][zip_code]': {
      maxLength: 9,
      required: false,
    },
    'shipment[sender_attributes][city]': {
      maxLength: 30,
      required: true,
    },
    'shipment[sender_attributes][country_code]': {
      maxLength: 10,
      required: true,
    },
    'shipment[sender_attributes][state_code]': {
      maxLength: 10,
      required: false,
    },
    'shipment[sender_attributes][phone_number]': {
      maxLength: 30,
      required: false,
      regex: Regex.phoneNumber,
      text: 'Phone number not formatted properly'
    },
    'shipment[sender_attributes][email]': {
      maxLength: 50,
      required: false,
      regex: Regex.email,
      text: 'Email not formatted properly'
    },

    // recipient
    'shipment[recipient_attributes][company_name]': {
      maxLength: 50,
      required: true,
    },
    'shipment[recipient_attributes][attention]': {
      maxLength: 50,
      warningLength: 30,
      required: true,
    },
    'shipment[recipient_attributes][address_line1]': {
      maxLength: 30,
      required: true,
    },
    'shipment[recipient_attributes][address_line2]': {
      maxLength: 30,
      required: false,
    },
    'shipment[recipient_attributes][address_line3]': {
      maxLength: 30,
      required: false,
    },
    'shipment[recipient_attributes][zip_code]': {
      maxLength: 9,
      required: false
    },
    'shipment[recipient_attributes][city]': {
      maxLength: 30,
      required: true,
    },
    'shipment[recipient_attributes][country_code]': {
      maxLength: 10,
      required: true,
    },
    'shipment[recipient_attributes][state_code]': {
      maxLength: 10,
      required: false,
    },
    'shipment[recipient_attributes][phone_number]': {
      maxLength: 30,
      required: false,
      regex: Regex.phoneNumber,
      text: 'Phone number not formated properly'
    },
    'shipment[recipient_attributes][email]': {
      maxLength: 50,
      required: false,
      regex: Regex.email,
      text: 'Email not formatted properly'
    },

    // shipment
    'shipment[description]': {
      maxLength: 30,
      required: false,
    },
    'shipment[customer_id]': {
      required: true,
    },
    'shipment[reference]': {
      maxLength: 18,
      required: false,
     },
     'shipment[remarks]': {
      required: false,
     }
   };

   var PickupSchema = {
     "shipment[pickup_options][from_time]": {
       regex: Regex.timeHHMM,
       text: 'Time not formatted properly (example 13:00)',
       required: true,
     },
     "shipment[pickup_options][to_time]": {
       regex: Regex.timeHHMM,
       text: 'Time not formatted properly (example 13:00)',
       required: true,
     },
     "shipment[pickup_options][contact_attributes][attention]": {
       maxLength: 22, // Limit for UPS PickupAddress/ContactName
       required: true,
     },
     "shipment[pickup_options][contact_attributes][company_name]": {
       maxLength: 27, // Limit for UPS PickupAddress/CompanyName
       required: true,
     },
     "shipment[pickup_options][description]": {
       maxLength: 11, // Limit for UPS PickupAddress/PickupPoint
       required: false,
     },
   };

  /* Listen on form submission and validate form
   */
  $('.validate-form').on('click', function(event) {
    event.preventDefault();
    var errors = cargoflux.validateForm();
    if (typeof errors === 'object') {
      var firstError = errors[0];
      var position   = firstError.topOffset - 50;

      $("html, body").animate({ scrollTop: position }, 'fast');
      return;
    }
    window.SubmitShipmentForm();
  });

  /* Listen for changes on fields marked for validation
   */
  $('.validate input, input.validate, textarea.validate, .validate select').on('input', function() {
    clearError(this);

    var name  = $(this).attr('name');
    var value = $(this).val();
    var schema = getSchemaForInput(name);

    if (value == undefined) {
      console.log('Field value is null [' + name + ']');
      return true;
    }

    if (schema[name] === undefined) {
      console.log('Field not specified in \'options\' [' + name + ']');
      return true;
    }

    var result = validateInput(name, value, schema);
    var error  = result.error;

    if (error) {
      showError(this, error);
    }

  });

  /* If valid returns true, else return an array of errors with their y-axis offset
   */
  cargoflux.validateForm = function() {
    var errors = [];

    $('.validate input, input.validate, textarea.validate, .validate select').each(function() {
      var name  = $(this).attr('name');
      var value = $(this).val();
      var schema = getSchemaForInput(name);

      if (value == undefined) {
        console.log('Field value is null [' + name + ']');
        return true; // same as 'continue', but required for $.each
      }

      if (schema[name] === undefined) {
        console.log('Field not specified in \'options\' [' + name + ']');
        return true; // same as 'continue', but required for $.each
      }

      var result = validateInput(name, value, schema);
      var error  = result.error;

      if (error !== undefined) {
        clearError(this);
        showError(this, error);

        errors.push({
          error: error,
          topOffset: $(this).offset().top
        });
      }
    });
    var valid = errors.length === 0;

    return valid ? true : errors;
  };

  /* Sets invalid class and appends error text to element
   */
  function showError(element, error) {
    $(element).addClass('invalid')
      .parent().addClass('field_with_errors')
      .append("<span class='error'>" + error + '</span>');
  }

  /* Clears invalid class and removes error text from element
   */
  function clearError(element) {
    $(element).parent()
      .removeClass('field_with_errors')
      .find('.error')
      .remove()
      .removeClass('invalid');
  }

  function getSchemaForInput(name) {
    if ($("input[name='shipment[request_pickup]']").is(":checked") && PickupSchema[name] !== undefined) {
      return PickupSchema;
    }

    return Schema;
  }

  /* Validates a single input field
   */
  function validateInput(name, value, schema) {
    try {
      options = getFieldOptions(name, schema);

      if (options !== undefined) {
        validatePresence(value, options);
        if (name == "shipment[recipient_attributes][attention]" | name == "shipment[sender_attributes][attention]" ){
          validateWarningLength(value, options);
        }else{
          validateLength(value, options);
        }
        validateRegex(value, options);
      }
    }
    catch (error) {
      return {
        field: name,
        error: error
      };
    }
    return true;
  }

  /* Validation helpers
   */

  function validatePresence(value, options) {
    if (options.required && isBlank(value)) {
      throw 'Field is required';
    }
  }

  function validateLength(value, options) {
    var maxLength = options.maxLength;
    if (maxLength && value.length > maxLength) {
      throw 'Field cannot exceed ' + maxLength + ' characters';
    }
  }

  function validateWarningLength(value, options) {
    var warningLength = options.warningLength;
    var maxLength = options.maxLength;
    if (warningLength && value.length > warningLength && value.length <= maxLength) {
      throw '<span style="color: yellow;">Warning: current shipment does not allow ' + warningLength + ' characters</span>';
    }else if(maxLength && value.length > maxLength) {
      throw '<span style="color: yellow;">Warning: current shipment does not allow ' + warningLength + ' characters</span><br>Field cannot exceed ' + maxLength + ' characters';
    }
  }


  function validateRegex(value, options) {
    var defaultText = options.text;
    var regex = options.regex;
    value = value.replace(/ /g,'');

    if (regex && value.length > 0 && !regex.test(value)) {
      throw defaultText || 'Field not formatted properly';
    }
  }

  /* Checks if the specified name exists in the validation object, return it if it does
   */
  function getFieldOptions(name, options) {
    options = options[name];
    if (options === undefined) {
      throw 'Field not specified in \'options\' [' + name + ']';
    }
    return options;
  }

  /* Helpers
   */

  function isBlank(str) {
    return (!str || /^\s*$/.test(str));
  }

});
$(函数(){
//如果不存在,则定义命名空间
if(货物流量的类型==‘未定义’){
cargoflux=新对象();
}
var Regex={
电子邮件:/^[a-zA-Z0-9.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/,
电话号码:/^\+?\d+$/,
timeHHMM://^\d\d:\d\d$/
};
变量模式={
//寄件人
“发货[发件人属性][公司名称]”:{
最大长度:50,
必填项:true
},
'发货[发件人属性][注意]:{
最大长度:50,
警告长度:30,
必填项:false
},
“发货[发件人属性][地址第1行]”:{
最大长度:30,
要求:正确,
},
“发货[发件人属性][地址第2行]”:{
最大长度:30,
必填项:false,
},
“发货[发件人属性][地址第3行]”:{
最大长度:30,
必填项:false,
},
“发货[发件人属性][邮政编码]”:{
最大长度:9,
必填项:false,
},
“发货[发件人属性][城市]”:{
最大长度:30,
要求:正确,
},
“发货[发件人属性][国家/地区代码]”:{
最大长度:10,
要求:正确,
},
“发货[发件人属性][状态代码]”:{
最大长度:10,
必填项:false,
},
'发货[发件人属性][电话号码]:{
最大长度:30,
必填项:false,
regex:regex.phoneNumber,
文字:“电话号码格式不正确”
},
“发货[发件人属性][电子邮件]”:{
最大长度:50,
必填项:false,
regex:regex.email,
文本:“电子邮件格式不正确”
},
//接受者
“发货[收件人属性][公司名称]”:{
最大长度:50,
要求:正确,
},
“发货[收件人属性][注意]:{
最大长度:50,
警告长度:30,
要求:正确,
},
“发货[收件人属性][地址第1行]”:{
最大长度:30,
要求:正确,
},
“发货[收件人属性][地址第2行]”:{
最大长度:30,
必填项:false,
},
“发货[收件人属性][地址第3行]”:{
最大长度:30,
必填项:false,
},
“发货[收件人属性][邮政编码]”:{
最大长度:9,
必填项:false
},
“发货[收件人属性][城市]”:{
最大长度:30,
要求:正确,
},
“发货[收件人属性][国家/地区代码]”:{
最大长度:10,
要求:正确,
},
“发货[收件人属性][状态代码]”:{
最大长度:10,
必填项:false,
},
'发货[收件人属性][电话号码]:{
最大长度:30,
必填项:false,
regex:regex.phoneNumber,
文本:“电话号码格式不正确”
},
“发货[收件人属性][电子邮件]”:{
最大长度:50,
必填项:false,
regex:regex.email,
文本:“电子邮件格式不正确”
},
//装运
“装运[说明]”:{
最大长度:30,
必填项:false,
},
“装运[客户标识]”:{
要求:正确,
},
“装运[参考]”:{
最大长度:18,
必填项:false,
},
“装运[备注]”:{
必填项:false,
}
};
var PickupSchema={
“装运[取货选项][从时间]”:{
regex:regex.timeHHMM,
文本:“时间格式不正确(示例13:00)”,
要求:正确,
},
“装运[提货选项][到时间]”:{
regex:regex.timeHHMM,
文本:“时间格式不正确(示例13:00)”,
要求:正确,
},
“发货[取货选项][联系方式][注意]”:{
maxLength:22,//UPS接收地址/联系人名称的限制
要求:正确,
},
“发货[取货选项][联系方式][公司名称]”:{
maxLength:27,//UPS接收地址/公司名称的限制
要求:正确,
},
“装运[提货选项][说明]”:{
maxLength:11,//UPS拾取地址/拾取点的限制
必填项:false,
},
};
/*听取表单提交并验证表单
*/
$('.validate form')。在('click',函数(事件){
event.preventDefault();
var errors=cargoflux.validateForm();
如果(错误类型===“对象”){
var firstError=错误[0];
var位置=firstError.topOffset-50;
$(“html,body”).animate({scrollTop:position},'fast');
返回;
}
window.SubmitShipmentForm();
});
/*侦听标记为验证的字段上的更改
*/
$('.validate input,input.validate,textarea.validate,.validate select')。on('input',function(){
clearError(这个);
var name=$(this.attr('name');
var值=$(this.val();
var schema=getSchemaForInput(名称);
如果(值==未定义){
log('字段值为null['+name+']');
返回true;
}
if(架构[名称]==未定义){
console.log('选项中未指定字段