简体   繁体   English

jQuery表单字段验证

[英]jQuery form field validation

I have the code below on my form fields to validate it's not empty. 我在表单字段上有以下代码来验证它是否为空。 If empty, a CSS error class is added. 如果为空,则添加CSS错误类。

if(!$('.order-modal input[name="address"]').val()){
 $('.order-modal input[name="address"]').addClass('ww-error');
  form_errors += 1;
}else{
 $('.order-modal input[name="address"]').removeClass('ww-error');
}

I also want to check if the same form field contains "PO box" or "PO box" or po box or po box and if it does change placeholder text and the error class. 我还想检查相同的表单字段是否包含“邮政信箱”或“邮政信箱”或邮政信箱或邮政信箱,以及是否确实更改了占位符文本和错误类。

The code below works in a way but not perfectly as I want it? 下面的代码以某种方式工作,但并非完全如我所愿?

if(!$('.order-modal input[name="address"]').val()){
  $('.order-modal input[name="address"]').addClass('ww-error');
    form_errors += 1;
}else if($('.order-modal input[name="address"]').val() == 'P.O. box'){
  $('.order-modal input[name="address"]').val('');
  $('.order-modal input[name="address"]').attr('placeholder', 'P.O. box not accepted');
  $('.order-modal input[name="address"]').addClass('ww-error');
    form_errors += 1;
}else{
  $('.order-modal input[name="address"]').removeClass('ww-error');
}

Thanks! 谢谢! /Robert /罗伯特·

there is no inbuilt hasValue function, instead of 没有内置的hasValue函数,而不是

$('.x').hasValue('Y')

use 采用

$('.x').val() == 'Y'

Complete code: 完整的代码:

var $fld = $('.order-modal input[name="address"]'), 
    val = $fld.val(), 
    fldError=false;
if ($.trim(val)==="") { // or add required attribute
  alert("Field is mandatory");
  fldError = true;
}
else {
  var po = val.indexOf('P.O. box') !=-1;
  if (po) {
    $fld.val('').attr('placeholder','POBox not allowed');
    fldError = true;
  }
}
$fld.toggleClass('ww-error',fldError);
if (fldError) form_errors += 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM