0

我有一个简单的表单,用户输入地址。jQuery验证地址 - Google Places API

在表单提交之前,我使用Places Api执行TextSearch,并将这些数据放入表单中隐藏的输入字段中,然后提交。

我想使用jQuery验证来验证表单,但我不知道如何获取Places数据。

我想我必须使用与验证submitHandler,但林不知道如何把我的代码在这里:

$("#myform").validate({ 
submitHandler: function(form) { 
    form.submit(); 
} 
}); 

这里是我的代码有没有验证插件:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Maps Test</title> 
     <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
     <style type="text/css"> 
      html { height: 100% } 
      body { height: 100%; margin: 0; padding: 0 } 
      #map_canvas { height: 100% } 
     </style> 
     <script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
     <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script> 
     <script src="http://code.jquery.com/jquery-latest.js"></script> 
     <script type="text/javascript"> 
      var map; 
      var service; 
      var infowindow; 
      var service; 
      var validated = false; 

      function initialize() { 
       var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316); 

       map = new google.maps.Map(document.getElementById('map_canvas'), { 
         mapTypeId: google.maps.MapTypeId.ROADMAP, 
         center: pyrmont, 
         zoom: 15 
        }); 

       service = new google.maps.places.PlacesService(map); 
      } 

      function textsearchcallback(results, status) { 
       if (status == google.maps.places.PlacesServiceStatus.OK) { 
        var place = results[0]; 
        var request = { 
         reference: place.reference 
        }; 
        service.getDetails(request, getdetailscallback); 
       } else { 
        alert("ERROR: NO RESULTS FOUND!"); 
       } 
      } 

      function getdetailscallback(place, status) { 
       if (status == google.maps.places.PlacesServiceStatus.OK) { 
        $("#placeinfo").val(JSON.stringify(place)); 
        validated = true; 
        $("#search-form").submit(); 
        validated = false; 
        $("#placeinfo").val(""); 
       } else { 
        alert("ERROR"); 
       } 
      } 

      function validateForm() { 
       var searchfield = $("#search-field").val(); 
       if (searchfield == null || searchfield == "") { 
        alert("Please enter address"); 
        return false; 
       } 
       if (validated) { 
        return true; 
       } else { 
        var request = { 
         query: searchfield 
        }; 
        service.textSearch(request, textsearchcallback); 
        return false; 
       } 
      } 
     </script> 
    </head> 

    <body onload="initialize()"> 
     <form id="search-form" name="input" action="html_form_action.asp" method="get" onsubmit="return validateForm()"> 
      <input autocomplete="off" placeholder="Address, Airport or Postcode..." id="search-field" size="50" type="text"><br> 
      <input type="hidden" name="placeinfo" id="placeinfo"> 
      <input type="SUBMIT" value="Search" /><br> 
     </form> 

     <div id="map_canvas" style="width:600px; height:400px"></div> 
    </body> 
</html> 

编辑:

这里是工作的代码小提琴:http://jsfiddle.net/robertdodd/txqnL/26/

+0

请解释什么_“获取位置数据连同它”_应该表示。你试图验证数据的参数究竟是什么? – Sparky

+1

我认为你的项目太大了,不能指望别人为你做所有的工作,并且JS中引用的大部分HTML都不见了。我建议您使用我的答案开始,使用jsFiddle构建工作演示,然后在SO上发布新的问题,无论何时卡住。请尽可能使其具体和简洁。请参阅http://sscce.org获取提示。 – Sparky

+0

谢谢你的提示,并为这个混乱的问题感到抱歉。以后我看过一些其他的小提琴演示问题,他们使得它更容易帮助! –

回答

1

选项1 - 客户端验证

这种方法是凌乱和黑客攻击的一位,我不建议这一点,除非你有没有其他办法。我建议使用another validation library或自己写,这是我打算自己做的。

简单的演示:http://jsfiddle.net/robertdodd/txqnL/27/

继承人一步一步发生了什么:

  1. 用户点击提交
  2. 形式的jQuery
  3. 验证
  4. 在提交处理我阻止形式提交和谷歌查找地址
  5. 当谷歌返回我填充隐藏的输入并设置validated = true
  6. 然后我重新提交表单,这一次,它提交,因为validated == true

选项2 - 服务器端验证:

另一种选择是服务器端验证,我建议作为无论如何都是备份。以下是如何将它与validate插件一起使用。

  1. 使用remote validation method从服务器获取
  2. 使用dataFilter的响应来检索响应的地图信息,把它变成隐藏的输入,然后通过返回要么“‘真’”或““错误信息更改响应“”因为远程确认需要一定的字符串(read here

继承人我的html代码:

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script> 
<script type="text/javascript"> 

    function initialize() { 
    $("#search-form").validate({ 
     rules: { 
     searchfield: { 
      required: true, 
      remote: { 
      url: "/validate", 
      type: "get", 
      dataFilter: function(data) { 
       var json = JSON.parse(data); 
       var placename = json.placename; 
       $('#placename').val(placename); 
       return '"' + json.result + '"'; 
      } 
      } 
     } 
     } 
    }); 
    } 
</script> 
</head> 

    <body onload="initialize()"> 
    <form id="search-form" > 
     <input autocomplete="off" placeholder="Enter a location" name="searchfield" id="searchfield" type="text" /><br/> 
     <input type="hidden" name="placename" id="placename" /> 
     <input type="submit" value="Search" /><br/> 
    </form> 
    <div id="successmessage"></div> 
    </body> 
</html> 

我希望这可以帮助别人!

0

如果我理解正确,您只是想将jQuery验证代替您自己的手动验证。是的,你可以从插件的submitHandler中调用你的函数,但是你的OP中缺少太多的代码用于你的Maps函数的工作演示。

这就像你需要做的事情。

$(document).ready(function() { 
    $('#myform').validate({ // initialize the plugin 
     // your rules and options, 
     ignore: [], // this option is required if you need to validate hidden inputs 
     submitHandler: function (form) { 
      // your functions here 
      form.submit(); // to submit the form when you're ready 
     } 
    }); 
}); 

另外,如果你需要使用AJAX提交表单无需页面重定向...

$(document).ready(function() { 
    $('#myform').validate({ // initialize the plugin 
     // your rules and options, 
     ignore: [], // this option is required if you need to validate hidden inputs 
     submitHandler: function (form) { 
      // ajax functions here 
      return false; // to block the normal form submit since you just did it with ajax 
     } 
    }); 
}); 

HTML:

您还需要删除onsubmit事件处理程序从您的HTML,因为它已经内置到jQuery Validate插件。

<form id="search-form" name="input" action="html_form_action.asp" method="get" 
onsubmit="return validateForm()"> 

将成为...

<form id="search-form" name="input" action="html_form_action.asp" method="get"> 

简化的演示:http://jsfiddle.net/wbdvc/


编辑:

关于jsFiddle demo in the OP's edit

以下if/then条件将永远不会正常工作。 By definition, the submitHandler is the callback for a valid form。换句话说,只有时间submitHandler功能将运行是表格已经测试“有效”,并在实际形式之前submit

submitHandler: function(form) { 
    if (validated) { 
     // address is validated and hidden input filled, so submit the form 
     alert('valid form submitted'); 
     validated = false; 
    } else { 
     // address is not validated yet, look up on Google Maps 
     var request = { 
      query: $("#searchfield").val() 
     }; 
     service.textSearch(request, textsearchcallback); 
    } 
    return false; 
} 

不是把这个逻辑的submitHandler里面的,你可以把它内addMethod ...

http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

这将创建一个你会使用像任何其他预定义的验证插件规则新规则。

+0

只有在发布我的答案后才看到您的修改,我会查看并回复给您,谢谢! –

+0

当我使用addMethod时,只要文本框被更改并失去焦点,函数就会被调用。这意味着在表单提交之前,我的回调最终会调用form.submit。在这里:http://jsfiddle.net/Homeliss/hX4FN/5/ –

+0

@Homeliss,现在我明白了你为什么最初将'validated'放在'submitHandler'内。我对这个插件了解很多,但我对Google地图代码并不熟悉。这个更好吗? http://jsfiddle.net/hX4FN/6/ – Sparky