使用jquery验证非必需输入的问题

Using JQuery, I want to validate non required input field if input field value exists.

value allow null in DB

<input type="text" class="form-control" name="moms_md_name" id="moms_md_name" value="">

Using JQuery

var mom_maiden_name = $('#moms_md_name').val();

1rst try

// …
} else if (maiden_name !== '' && maiden_name !== null) {
  if (!maiden_name.match(/^(?=.*[a-z]).{3,20}$/)) {
    alert("Mother maiden name not properly entered!");
  }
// …

Now when I:

  • Leave the field blank/empty, it works and I get result
  • Disable JQuery validation I get result too
  • Enter a wrong input like 222 or aa, I get error message
  • Enter a correct input, I get no result at all <- ?

2nd try

// …
 } else if(maiden_name !== '' && maiden_name !== null){
   if (
      $('#moms_md_name').val()
      && !mom_maiden_name.match(/^(?=.*[a-z]).{3,20}$/)) {
          alert("Mother maiden name not properly entered!");
   }
// …

Now when I:

  • Leave the field blank/empty, it works and I get result
  • Disable JQuery validation I get result too
  • Enter a wrong input like 222 or aa, I get error message
  • Enter a correct input, I get no result at all <- ?

PHP - looking for something equivalent of below (disable for testing)

// …
else if(!empty($_POST['moms_md_name'])) {
  if (
    isset($_POST['moms_md_name'])
    && !preg_match('%^[A-Za-z\.\' \-]{2,30}$%', $_POST['moms_md_name'])
    ) {
        echo "Mother maiden name need to be properly entered!";
        exit();
    }
}
// …

Specifying a valid value gives no message/console log.
Though it works if I disable JQuery and enable PHP validation.

I'll begin with your Javascript code:

    else if (maiden_name !== '' && maiden_name !== null) {
      if (!maiden_name.match(/^(?=.*[a-z]).{3,20}$/)) {
         alert("Mother maiden name not properly entered!");
   }

First you should verify if the value is empty then do your code:

var mom_maiden_name = $('#moms_md_name').val();
if (mom_maiden_name  == '' || mom_maiden_name.match(/^(?=.*[a-z]).{3,20}$/)) {
    //Validation passed 
} else {
    //Validation failed again
}

I'm not sure what the regex should do but I assume it's correct.

Second, looking at your PHP code, I see a wrong validation there. If you first check a value for not being empty, you can automatically be assured that it's set. If you want to keep your code, you should invert those 2 conditions in 'if' :

if(isset($_POST['moms_md_name'])) {
   if (!empty($_POST['moms_md_name']) && !preg_match('%^[A-Za-z\.\' \-]{2,30}$%', $_POST['moms_md_name'])) {
      echo "Mother maiden name need to be properly entered!";
      exit();
   }
} 

Again, I don't know what the regex does so I will assume it's correct.