You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codeigniter & Ajax:JavaScript表单验证条件语句疑问解析

Understanding the Form Validation Logic in Your Codeigniter Ajax Script

Hey there! Let's unpack that form validation logic you're confused about—it's a simple (but a bit quirky) way to check if all required fields are filled out.

First, let's look at your code snippet to set the context:

$('#btnSave').click(function(){
 var url = $('#myForm').attr('action');
 var data = $('#myForm').serialize();
 //validate form
 var empoyeeName = $('input[name=txtEmployeeName]');
 var address = $('textarea[name=txtAddress]');
 var result = '';
 if(empoyeeName.val()==''){
 empoyeeName.parent().parent().addClass('has-error');
 }else{
 empoyeeName.parent().parent().removeClass('has-error');
 result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
 }
 if(address.val()==''){
 address.parent().parent().addClass('has-error');
 }else{
 address.parent().parent().removeClass('has-error');
 result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
 }
 if(result=='12'){ //HERE IS WHAT IM CONFUSED
 $.ajax({
 type: 'ajax',
 method: 'post',
 url: url,
 data: data,
 async: false,
 dataType: 'json',
 success: function(response){
 if(response.success){
 $('#myModal').modal('hide');
 $('#myForm')[0].reset();
 if(response.type=='add'){
 var type = 'added'
 }else if(response.type=='update'){
 var type ="updated"
 }
 $('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
 showAllEmployee();
 }else{
 alert('Error');
 }
 },
 error: function(){
 alert('Could not add data');
 }
 });
 }
 });

What's the Purpose of the result String?

The developer who wrote this code is using a string to track which fields passed validation:

  • When the employee name field is not empty, they append '1' to result. The 1 here is just an arbitrary marker—it could be any character (like 'a' or 'x') as long as it's unique to this field.
  • When the address field is not empty, they append '2' to result. Again, 2 is just a unique marker for the address field.

By checking if result == '12', they're verifying that both fields passed validation:

  • If only the name was filled, result would be '1'
  • If only the address was filled, result would be '2'
  • If both are filled, result becomes '12' (since we check the name first, then the address)

Why This Approach Works (But Isn't Ideal)

This method works for your current 2-field form, but it has some downsides:

  • It depends on the order of validation: if you ever reorder the checks (validate address first, then name), result would be '21' instead of '12', and your condition would fail.
  • It doesn't scale well: if you add more fields, you'd have to append more characters and update the condition to something like '123' or '1234', which gets messy fast.

A Better Alternative

Instead of string concatenation, you can use clearer, more maintainable approaches:

Option 1: Use a Counter

Track how many fields passed validation with a number:

var validFields = 0;

if(empoyeeName.val()!=''){
 empoyeeName.parent().parent().removeClass('has-error');
 validFields++;
} else {
 empoyeeName.parent().parent().addClass('has-error');
}

if(address.val()!=''){
 address.parent().parent().removeClass('has-error');
 validFields++;
} else {
 address.parent().parent().addClass('has-error');
}

// Check if all required fields are valid
if(validFields == 2){
 // Trigger Ajax request here
}

Option 2: Use Boolean Flags

Use separate boolean variables to track each field's validity:

var isNameValid = empoyeeName.val() != '';
var isAddressValid = address.val() != '';

// Update UI based on validity
if(isNameValid){
 empoyeeName.parent().parent().removeClass('has-error');
} else {
 empoyeeName.parent().parent().addClass('has-error');
}

if(isAddressValid){
 address.parent().parent().removeClass('has-error');
} else {
 address.parent().parent().addClass('has-error');
}

// Check if both are valid
if(isNameValid && isAddressValid){
 // Trigger Ajax request here
}

Both of these methods are easier to read, scale better, and don't depend on the order of your validation checks.

内容的提问来源于stack exchange,提问作者user11174163

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:23:42