简体   繁体   中英

Activation of the HTML5 Pattern Attribute with websockets

As a total newbie to web-based programming, I'm having trouble understanding why the pattern attribute field below fails to check the validity of the text field due to my javascript.

<form id="aForm">
    <input type="text" pattern="^[ a-zA-Z0-9,#.-]+$" id="address" title="Standard address"/>        
<input type="submit" id="open" value="Start"/>
</form>

The form contents are then sent to a javascript file which then sends it to the server via a websocket as in the code fragment below. However it ignores validating the form through the pattern attribute.

 $(document).ready(function() {

    $("#open").click(function(evt) {          
          evt.preventDefault();
          var form = $('#aForm').serialize();
          webSocket = new WebSocket("ws://localhost:9999/mh");
          webSocket.onopen = function()
          {
             webSocket.send(form);
          };
          REST OF CODE....

It seems that for some reason this prevents the text from being checked before it's sent. I would like to know why and how to ensure that the form is validated by the pattern attribute.

Thanks

The HTML5 form validation is only performed when you're trying to actually submit the form , or when you explicitly use JavaScript to validate it 1 .

Since your JavaScript is bound to a different event (button click), form validation is not performed at that point. You can solve this by:

  1. binding your submission to the form's submit event instead of button click, or
  2. using the form validation API at the very beginning of your script.

I strongly recommend the first option. It makes more semantic sense and works right when the form is submitted though other methods (I don't remember if the button click will be simulated when someone presses Enter in the text field, and it definitely won't be triggered if JavaScript calls $('#aForm').submit() programmatically...).


1 At least, those are the only places I noticed - it's possible there are other events/circumstances when validation is done as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM