I've got a validation that requires an ajax call, the validation is done both on the field change event and on the form submit so I've got a named function that does the validation and just call that function from both places.
The problem I've got though is that when the form is submitted there is another validation that needs to happen via ajax, this one may or may not be required based on a form value.
The validation process I'd like to follow when the form is submitted is
make sure all the required fields have an entry
if all the fields are OK do the mandatory ajax call
if the mandatory call returns an OK, then do the optional one, if required
I cant put the optional ajax in the callback of the required one since the required one is called at other times other than when the form is submitted and I'd prefer not to duplicate the required ajax code.
Here's the code I have so far:
- $(document).ready(function(){
- $("#nextBtn").click(function() {
- isValid();
- });
- $("#poNumber").change(function() {
- if ($("#poNumber").val() != "") {
- var temp = validatePO();
- }
- });
- });
- function isValid(){
- var isValid = true;
- var emailReg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
- $(".isReq").removeClass("inpNeeded");
- ...
- if ($("#contactName").val() == "") {
- isValid = false;
- $("#contactName").addClass("inpNeeded");
- }
- if ($("#phone").val() == "") {
- isValid = false;
- $("#phone").addClass("inpNeeded");
- }
- ...
- if (isValid) {
- isValid = validatePO(); // this one needs to get called
-
- // this is the optional one
- if ($("#frfqNumber").val() != "") {
- $.post("include/verifyFRFQNumber.asp",
- {rfqID: $("#frfqNumber").val()},
- function(data){
- if (data.frfqStatus == "1") {
- alert("The FRFQ number you entered does not exist.\nPlease double check the number.");
- isValid = false;
- }
- if (isValid) {
- $("#poForm").submit();
- } else {
- alert("Please make sure the highlighted fields have an entry.");
- }
-
- },
- "json"
- );
- } else if (isValid) {
- $("#poForm").submit();
- }
- } // end if isValid
- }
-
- function validatePO() {
- $.get(
- "include/validatePONumber.asp",
- {poNumber: $("#poNumber").val()},
- function(data) {
- if (data.isUsed == "yes") {
- alert("There is an existing purchase order on file with that PO Number.\nPlease enter a new number for this order.");
- $("#poNumber").addClass("inpNeeded");
- } else {
- $("#poNumber").removeClass("inpNeeded");
- }
- }
- );
- }
I'm not sure if when() is the answer since the second call may or may not be needed.
I can make it work, but it would require duplicating the required ajax and then nesting the optional one in the call back, or I could make them all async false, but neither of those solutions seems quite right.
Other options? Thoughts?
Thanks everyone,
Dave