Manual form validation in MVC 3 and JQuery

后端 未结 4 1422
旧巷少年郎
旧巷少年郎 2020-12-09 05:01

I want to be able to trigger form validation on the client side when the user selects the \"GO\" button. Currently when the \"GO\" button is selected it does not validate th

相关标签:
4条回答
  • 2020-12-09 05:29

    I don't know if this is the best/most efficient way, but I do it by validating each element individually in my own function.

    jQuery(document).ready(function () {
    
        $("#butValidateForm").button().click(function () { return IsMyFormValid(); });
        $('#myForm').validate();
    
    }
    
    function IsMyFormValid() {
    
        var isValid = false;
    
        isValid = $('#myForm').validate().element($('#UserName '));
        isValid = ($('#myForm').validate().element($('#Password '))) ? isValid : false;
        isValid = ($('#myForm').validate().element($('#EmailAddress'))) ? isValid : false;
    
        return isValid;
    }
    

    It would be great to let it validate automagically, but I always seem to run into some weird business logic rule that doesn't get caught by the generic validation methods. Doing it this way lets me control all of the validation the way I want to, but relying on built in validation most of the time.

    0 讨论(0)
  • 2020-12-09 05:30

    Not sure if you figured this out yet, but I ran into the same thing in IE with $("#myForm").submit. Use live:

    $("#myForm").live('submit', function (e) {
        var val = $('#myForm').validate(); //<--added the semi-colon
        val.showErrors();
        alert(val.valid());
    
    
        e.preventDefault();
    });
    
    0 讨论(0)
  • 2020-12-09 05:48

    Its not working in IE because you are missing a semi-colon:

    var val = $('#myForm').validate()
    
    0 讨论(0)
  • 2020-12-09 05:49
    <script type="text/javascript">
        $(function () {
            $("#butValidateForm").click(function (event) {
    
                var isValid = $('#myForm').valid();
                if(isValid)
                {
                   //do something before submit the form
                   $('#myForm').submit();
                }else{
                   alert('validation failed'); 
                }
                event.preventDefault();
            })
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题