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:09

I found this solution to work for me. Just call a javascript function like this:

action="javascript:myFunction();"

Then you have the html5 validation... really simple :-)

查看更多
时光乱了年华
3楼-- · 2019-01-01 05:09
$(document).ready(function () {
    var obj = {};
    $("#click_radio").click(function () {
        //Function to get the dropdown list using AJAX
        $.ajax({
            type: "get",
            url: "json/droplist1.json",
            dataType: "json",
            success: function (res) {
                populateDropDown1(res)
            }
        })
        $.ajax({
            type: "get",
            url: "json/droplist2.json",
            dataType: "json",
            success: function (res) {
                populateDropDown2(res)
            }
        })
        $.ajax({
            type: "get",
            url: "json/droplist3.json",
            dataType: "json",
            success: function (res) {
                populateDropDown3(res)
            }
        })
        //Internal function to populate the dropdown list
        function populateDropDown1(data) {
            $.each(data, function (index, val) {
                $("#list1").append('<option key=' + val.key + '>' + val.value + '</option>');
            });
        }
        function populateDropDown2(data) {
            $.each(data, function (index, val) {
                $("#list2").append('<option key=' + val.key + '>' + val.value + '</option>');
            });
        }
        function populateDropDown3(data) {
            $.each(data, function (index, val) {
                $("#list3").append('<option key=' + val.key + '>' + val.value + '</option>');
            });
        }
        $('#person_form').show();
    })

    $("#submit").click(function (e) {
        e.preventDefault();
        var namefl = 0, numbf = 0;
        var namef = $("#name").val();
        var phnenumb = $("#numb").val();
        var list11 = $("#list1").val();
        var list12 = $("#list2").val();
        var list13 = $("#list3").val();


        localStorage.setItem('name', $("#name").val());
        localStorage.setItem('number', $("#numb").val());
        localStorage.setItem('list11', $("#list1").val());
        localStorage.setItem('list12', $("#list2").val());
        localStorage.setItem('list13', $("#list3").val());
        if (namef.length < 2 || namef.length > 15) {
            $("#nameerror").show();
            namefl = 0;
        }
        else {
            namefl = 1;
            $("#nameerror").hide();
        }
        //    if(phnenumb.length<10 || phnenumb.isNaN()){ 
        //       $("#name").addClass('error');  
        //   }
        //   else{
        //       $("#name").removeClass('error'); 
        //   }
        if (namefl == 1) {
            $("#person_form").load("partials.html");
        }

        $.ajax({
            type: "get",
            dataType: "json",
            url: "json/drag_droplist.json",
            success: function (res) {
                populateSecondPageList(res);
            }
        })


    })
    //populate data in the first list box
    function populateSecondPageList(result) {
        $.each(result, function (index, value) {
            $("#draglist").append('<li draggable="true" ondragstart="drag(event)" id="drag' + index + '" class="list-item"><span class="key">' + value.key + ' </span><span class="value">' + value.value + '</span></li>');
        })

    }

    $(document).on("click", "#submitList", function () {
        var namef = localStorage.getItem('name');
        var numb = localStorage.getItem('number');
        var list1f = localStorage.getItem('list11');
        var list2f = localStorage.getItem('list12');
        var list3f = localStorage.getItem('list13');
        var dropname = localStorage.setItem('drpval', sampleData.value);
        var dropnam = localStorage.getItem('drpval');
        var obj = { namef, numb, list1f, list2f, list3f, dropnam };
        console.log(obj);
        $.ajax({
            type: "POST",
            data: obj,
            dataType: "json",
            url: "https://reqres.in/api/users",
            success: function (result) {

                $("#myModal").modal('show');
                $('#myModal .modal-body').html("<p>" + obj.namef + "</p> <p> " + obj.numb + "</p><p>" + obj.list1f + "</p><p>" + obj.list2f + "</p><p>" + obj.list3f + "</p><p>" + obj.dropnam + "</p>");

            },
            error: function (result) {
                alert('error');
                console.log(result);
            }
        });
    })

});


//drag and drop
var dragleave = "";
var sampleData = {};
function allowDrop(ev) {
    ev.preventDefault();
    ev.target.innerHTML = "";
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    $(".list-unstyled li").css("display", "block");
    ev.preventDefault();
    // console.log(ev.target);
    var data = ev.dataTransfer.getData("text");
    // console.log(document.getElementById(data));
    ev.target.innerHTML = document.getElementById(data).innerHTML;

    $(".list-unstyled #" + data).css("display", "none");
    //console.log($("#"+data).html());  

    if ($("#" + data).html()) {
        sampleData = { "key": $("#" + data + " .key").html(), "value": $("#" + data + " .value").html() };
    }
}
查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 05:12

Here is a more general way that is a bit cleaner:

Create your form like this (can be a dummy form that does nothing):

<form class="validateDontSubmit">
...

Bind all forms that you dont really want to submit:

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

Now lets say you have an <a> (within the <form>) that on click you want to validate the form:

$('#myLink').click(function(e){
  //Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
  //has .validateDontSubmit class
  var $theForm = $(this).closest('form');
  //Some browsers don't implement checkValidity
  if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
     return;
  }

  //if you've gotten here - play on playa'
});

Few notes here:

  • I have noticed that you don't have to actually submit the form for validation to occur - the call to checkValidity() is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer.
  • The thing that triggers the validation does not have to be within the <form>. This was just a clean and flexible way to have a general purpose solution..
查看更多
泪湿衣
5楼-- · 2019-01-01 05:12

This way works well for me:

  1. Add onSubmit attribute in your form, don't forget to include return in the value.

    <form id='frm-contact' method='POST' action='' onSubmit="return contact()">
    
  2. Define the function.

    function contact(params) {
        $.ajax({
            url: 'sendmail.php',
            type: "POST",
            dataType: "json",
            timeout: 5000,
            data: { params:params },
            success: function (data, textStatus, jqXHR) {
                // callback
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR.responseText);
            }
        });
    
        return false;
    }
    
查看更多
低头抚发
6楼-- · 2019-01-01 05:13
$("#form").submit(function() { $("#saveButton").attr("disabled", true); });

not a best answer but works for me.

查看更多
查无此人
7楼-- · 2019-01-01 05:15

You don't need jQuery to achieve this. In your form add:

onsubmit="return buttonSubmit(this)

or in JavaScript:

myform.setAttribute("onsubmit", "return buttonSubmit(this)");

In your buttonSubmit function (or whatver you call it), you can submit the form using AJAX. buttonSubmit will only get called if your form is validated in HTML5.

In case this helps anyone, here is my buttonSubmit function:

function buttonSubmit(e)
{
    var ajax;
    var formData = new FormData();
    for (i = 0; i < e.elements.length; i++)
    {
        if (e.elements[i].type == "submit")
        {
            if (submitvalue == e.elements[i].value)
            {
                submit = e.elements[i];
                submit.disabled = true;
            }
        }
        else if (e.elements[i].type == "radio")
        {
            if (e.elements[i].checked)
                formData.append(e.elements[i].name, e.elements[i].value);
        }
        else
            formData.append(e.elements[i].name, e.elements[i].value);
    }
    formData.append("javascript", "javascript");
    var action = e.action;
    status = action.split('/').reverse()[0] + "-status";
    ajax = new XMLHttpRequest();
    ajax.addEventListener("load", manageLoad, false);
    ajax.addEventListener("error", manageError, false);
    ajax.open("POST", action);
    ajax.send(formData);
    return false;
}

Some of my forms contain multiple submit buttons, hence this line if (submitvalue == e.elements[i].value). I set the value of submitvalue using a click event.

查看更多
登录 后发表回答