简体   繁体   中英

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.

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

$('.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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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