Codeigniter & Ajax:JavaScript表单验证条件语句疑问解析
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'toresult. The1here 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'toresult. Again,2is 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,
resultwould be'1' - If only the address was filled,
resultwould be'2' - If both are filled,
resultbecomes'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),
resultwould 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

