How to force a html5 form validation without submi

2019-01-01 05:00发布

I have this form in my app and I will submit it via AJAX, but I want to use HTML5 for client-side validation. So I want to be able to force the form validation, perhaps via jQuery.

I want to trigger the validation without submitting the form. Is it possible?

20条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 05:20
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <link rel="stylesheet" href="assets/css/style.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

  <script src="scripts/app.js"></script>
</head>

<body>
    <div class="container">
    <div class="row">
        <label><input type="radio" id="click_radio" value="click">click</label>
    </div>
    <div class="row">
        <div class="col-md-8" id="person_form">
            <form>
                <fieldset>
                    <p><strong>pick your colour</strong></p>
                    <div class="row">
                        <div class="col-md-4 form-group">
                            <label>color</label>
                            <select class="form-control" id="list1"></select>
                        </div>
                        <div class="col-md-4 form-group">
                            <label>sports</label>
                            <select class="form-control" id="list2"></select>
                        </div>
                        <div class="col-md-4 form-group">
                            <label>books</label>
                            <select class="form-control" id="list3"></select>
                        </div>

                    </div>
                    <div class="row">
                        <div class="col-md-6" >
                            <label class="col-md-12">name</label>
                            <input type="text" class="col-md-12 form-control" id="name">
                             <p id="nameerror"> This field is required</p>
                        </div>
                        <div class="col-md-6">
                            <label>phone number</label>
                            <input type="text" class="col-md-12 form-control" id="numb">
                        </div>
                    </div>
                    <div class="row">
                        <button class="btn btn-success pull-right" id="submit" type="submit">go to code</buttn>
                    </div>
                </fieldset>
            </form>

        </div>
        <div class="row second">
              <div class="col-md-12">
                  <div class="row">
                      <div class="col-md-6">
                          <ul id="draglist"  class="list-unstyled">

                          </ul>
                      </div>
                      <div class="col-md-6">
                          <ul id="droplist" ondrop="drop(event)" ondragover="allowDrop(event)" ondragleave="dragLeave(event)">

                          </ul>
                      </div>
                  </div>
              </div>
              <div class="col-md-12">
                  <div class="row">
                      <div class="col-md-6"></div>
                      <div class="col-md-6">
                          <button class="btn btn-success pull-right" id="submitList">Submit</button>
                      </div>
                  </div>
              </div>
          <div class="modal fade" id="myModal" role="dialog">
              <div class="modal-dialog">
             <!-- Modal content-->
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Confirmation</h4>
                  </div>
                  <div class="modal-body">
                    <p>You have successfully completed the application!!!</p>
                  </div>
                  <div class="modal-footer footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                  </div>
                </div>

              </div>
            </div>
          </div>
        <div class="col-md-4 pull-right">
            <h1>Benefits</h1>
            <ul>
                <li>item 1</li>
                <li>item 2</li>
                <li>item 3</li>
                <li>item 4</li>
                <li>item 5</li>
            </ul>
        </div>

    </div>

</div>
</body>
</html>
查看更多
情到深处是孤独
3楼-- · 2019-01-01 05:21

You speak of two different things "HTML5 validation" and validation of HTML form using javascript/jquery.

HTML5 "has" built-in options for validating a form. Such as using "required" attribute on a field, which could (based on browser implementation) fail form submission without using javascript/jquery.

With javascrip/jquery you can do something like this

$('your_form_id').bind('submit', function() {
   // validate your form here
   return (valid) ? true : false;
});
查看更多
只若初见
4楼-- · 2019-01-01 05:23

I know this has already been answered, but I have another possible solution.

If using jquery, you can do this.

First create a couple of extensions on jquery so you can resuse these as needed.

$.extend({
    bypassDefaultSubmit: function (formName, newSubmitMethod) {
        $('#'+formName).submit(function (event) {
            newSubmitMethod();
            event.preventDefault();
        }
    }
});

Next do something like this where you want to use it.

<script type="text/javascript">
    /*if you want to validate the form on a submit call, 
      and you never want the form to be submitted via
      a normal submit operation, or maybe you want handle it.
    */
    $(function () {
        $.bypassDefaultSubmit('form1', submit);
    });
    function submit(){ 
        //do something, or nothing if you just want the validation
    }

</script>
查看更多
笑指拈花
5楼-- · 2019-01-01 05:27
<!DOCTYPE html>
<html>

<head>
                <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
                <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
                <link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
                <title></title>
                <style>
                                .div{
                                width:100px;
                                height:100px;
                                border:1px solid black;
                                }
                                #div1{
                                width:20px;
                                height:20px;
                                background: red;
                                }
                                #div2{
                                width:20px;
                                height:20px;
                                background: blue;
                                }
                                #div3{
                                width:20px;
                                height:20px;
                                background: black;
                                }
                </style>
                                <script> 
                                var initial="";      
                                function allowDrop(e)
                                {
                                                e.preventDefault();
                                }
                                function drag(e){
                                                e.dataTransfer.setData("div",e.target.id);
                                }
                                function drop(e)
                                {                                              
                                                e.preventDefault();
                                                var data = e.dataTransfer.getData("div");
                                                if(initial=="")
                                                {
                                                initial = $("#"+data);
                                                e.target.appendChild($("#"+data)[0]);
                                                }else{
                                                $("#draghere").append(initial);
                                                e.target.appendChild($("#"+data)[0]);
                                                initial = $("#"+data);
                                                }
                                }
  //                                function drop(e)
  //                               { 
  // e.preventDefault();
  // var data = e.dataTransfer.getData("div");
  // e.target.appendChild($("#"+data)[0]);
  //                                }
                                $(document).ready(function(){

                                });
                </script>
</head>

<body>
                <div class="div" id="draghere" ondragover="allowDrop(event)" ondrop="drop(event)">
                <div class="item" id="div1" draggable="true" ondragstart="drag(event)">
                </div>
        <!--         <div class="item" id="div2" draggable="true" ondragstart="drag(event)">
                </div>
                <div class="item" id="div3" draggable="true" ondragstart="drag(event)">
                </div> -->
                </div>   
                <div class="div" id="draghere1" ondragover="allowDrop(event)" ondrop="drop(event)"></div>  
                <input type="text" name="asfa" id="tt" maxlength="10" onkeypress="return (event.charCode >= 47 && event.charCode <= 57) || event.charCode == 43 || event.charCode == 45" onpaste="return (event.charCode >= 47 && event.charCode <= 57) || event.charCode == 43 || event.charCode == 45">
</body>

</html>
查看更多
人间绝色
6楼-- · 2019-01-01 05:29

I had a rather complex situation, where I needed multiple submit buttons to process different things. For example, Save and Delete.

The basis was that it was also unobtrusive, so I couldn't just make it a normal button. But also wanted to utilize html5 validation.

As well the submit event was overridden in case the user pressed enter to trigger the expected default submission; in this example save.

Here is the efforts of the processing of the form to still work with/without javascript and with html5 validation, with both submit and click events.

jsFiddle Demo - HTML5 validation with submit and click overrides

xHTML

<form>
    <input type="text" required="required" value="" placeholder="test" />
    <button type="submit" name="save">Save</button>
    <button type="submit" name="delete">Delete</button>
</form>

JavaScript

//wrap our script in an annonymous function so that it can not be affected by other scripts and does not interact with other scripts
//ensures jQuery is the only thing declared as $
(function($){
    var isValid = null;
    var form = $('form');
    var submitButton = form.find('button[type="submit"]')
    var saveButton = submitButton.filter('[name="save"]');
    var deleteButton = submitButton.filter('[name="delete"]');

    //submit form behavior
    var submitForm = function(e){
        console.log('form submit');
        //prevent form from submitting valid or invalid
        e.preventDefault();
        //user clicked and the form was not valid
        if(isValid === false){
            isValid = null;
            return false;
        }
        //user pressed enter, process as if they clicked save instead
        saveButton.trigger('click');
    };

    //override submit button behavior
    var submitClick = function(e){
        //Test form validitiy (HTML5) and store it in a global variable so both functions can use it
        isValid = form[0].checkValidity();
        if(false === isValid){
            //allow the browser's default submit event behavior 
            return true;
        }
        //prevent default behavior
        e.preventDefault();
        //additional processing - $.ajax() etc
        //.........
        alert('Success');
    };

    //override submit form event
    form.submit(submitForm);

    //override submit button click event
    submitButton.click(submitClick);
})(jQuery);

The caveat to using Javascript is that the browser's default onclick must propagate to the submit event MUST occur in order to display the error messages without supporting each browser in your code. Otherwise if the click event is overridden with event.preventDefault() or return false it will never propagate to the browser's submit event.

The thing to point out is that in some browsers will not trigger the form submit when the user presses enter, instead it will trigger the first submit button in the form. Hence there is a console.log('form submit') to show that it does not trigger.

查看更多
人间绝色
7楼-- · 2019-01-01 05:33

To check all the required fields of form without using submit button you can use below function.

You have to assign required attribute to the controls.

  $("#btnSave").click(function () {
    $(":input[required]").each(function () {                     
        var myForm = $('#form1');
        if (!$myForm[0].checkValidity()) 
          {                
            $(myForm).submit();              
          }
        });
  });
查看更多
登录 后发表回答