简体   繁体   中英

Jquery Validation Don't work on Submit if Submit has some Code

I am using MVC Data Anotation with jquery validation for validating my form. It works perfectly on submit but if I write some code on submit click, it doesn't validate it. Why so? Where am I wrong? I am using jquery.validate.unobtrusive.min.js and jquery.validate.min.js

I am not getting any kind of error. Just in my case, jquery validation stop working on submit if I put some code on submit click.

HTML:

<form action="/Login/ChangePassword" id="changePasswordForm" method="post">  <div id="changePasswordDiv" class="col-md-6">
  <div class="form-group">
    <label class="control-label col-lg-7" for="Current_password_:">Current password :</label>
    <div class="col-lg-5">
    <input MaxLength="8" class="form-control" data-val="true" data-val-required="Please enter current password." id="OldPassword" name="OldPassword" placeholder="Enter Your Current Password" type="password" value="" />
    <span class="field-validation-valid" data-valmsg-for="OldPassword" data-valmsg-replace="true" id="vOldPassword" style="color:red"></span>
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-lg-7" for="New_password_:">New password :</label>
    <div class="col-lg-5">
    <input MaxLength="8" MinLength="4" class="form-control" data-val="true" data-val-required="Please enter new password." id="NewPassword" name="NewPassword" placeholder="Enter Your New Password" type="password" value="" />
    <span class="field-validation-valid" data-valmsg-for="NewPassword" data-valmsg-replace="true" id="vNewPassword" style="color:red"></span>
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-lg-7" for="Confirm_password_:">Confirm password :</label>
    <div class="col-lg-5">
    <input MaxLength="8" MinLength="4" class="form-control" data-val="true" data-val-equalto="The new and confirm passwords should match." data-val-equalto-other="*.NewPassword" data-val-required="Please enter confirm password." id="ConfirmPassword" name="ConfirmPassword" placeholder="Confirm Password" type="password" value="" />
    <span class="field-validation-valid" data-valmsg-for="ConfirmPassword" data-valmsg-replace="true" id="vConfPass" style="color:red"></span>
    </div>
  </div>
  <div class="form-group">
    <div class="col-lg-7"></div>
    <div class="col-lg-5">
    <input type="submit" id="btnChangePassword" class="btn btn-default btn-primary" value="Save"/>
    </div>
  </div>
  <div class="form-actions col-right">
  </div>
  </div>
</form>

SCRIPT:

<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/Custom/CustomValidation.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
  debugger;
  var validator = $('#changePasswordForm').validate({
    rules: {
    NewPassword: { IsNotEqualString: "#OldPassword" }
    },
    messages: {
    NewPassword: { IsNotEqualString: "New Passowrd can't same as Current Password." }
    }
  });
  });
</script>

CustomValidation.js

jQuery.validator.addMethod('IsNotEqualString', function (value, element, param) {  alert(param)
  return this.optional(element) || value.toLowerCase() != $(param).val().toLowerCase();
}, "");

Here is whole code if you want to check.

Quote OP :

"I am using MVC Data Anotation with jquery validation for validating my form. It works perfectly on submit but if I write some code on submit click, it doesn't validate it. Why so? Where am I wrong? I am using jquery.validate.unobtrusive.min.js and jquery.validate.min.js "

The jQuery Validation plugin automatically captures the click of the submit button, does its validation, displays errors, and then submits the form if valid. You're going wrong by putting an onclick handler within the submit button. Your onclick="return abc()" simply over-rides the click handler built into the jQuery Validation plugin.

"I am not getting any kind of error. Just in my case, jquery validation stop working on submit if I put some code on submit click."

Of course you're not getting an error. That's because everything is working the way you've programmed it. Your onclick="return abc()" takes over from the jQuery Validation plugin. It looks like your abc() function is manual validation. Why would you use the jQuery Validation plugin to validate the form and also write your own function to validate the form? This makes no sense.

The plugin provides a method for writing your own rules . Remove the onclick="return abc()" from your submit button to let the jQuery Validation plugin operate normally. Remove the abc() function and replace it with a custom rule/method for the jQuery Validation plugin.

Also with jQuery, you should never need to use an event handler within HTML again. Events can be handled solely within your jQuery code.

$('#element').on('click', function() {
    // your code
});

This is just an example, because in your case, you don't need a click handler function at all.

I take the and comment inside the function.

  1. First error when you using Jquery inside the function's Javascript load the library of Jquery. Where you can find on google that share on the site or on Jquery

  2. Miss before the function abc(){ this sentence

      `$(document).ready(function () {` 

    And add } for closing before the closing tag </script>

  3. Reading the site of jquery.validate.js this is tested of these version:

1.6.4, 1.7.2, 1.8.3, 1.9.0 ( link ).

Then I suggest of use this library of Jquery 1.9.0 and Site

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

<script type="text/javascript">
     $(document).ready(function () {
    function abc() {
       // debugger;
        var validated = true;
        var password = $.trim($('#NewPassword').val());
        var oldPassword = $.trim($('#OldPassword').val());
        if (password == oldPassword) {
            $('#vNewPassword').text("New Password can't be same as Old Password.");
            validated = false;
        } else {

            //if password contains both lower and uppercase characters
            if (!password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
                validated = false;
            }
            //if it has numbers and characters, increase strength value
            if (!password.match(/([0-9])/)) {
                validated = false;
            }
            //if it has one special character
            //if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)){
            //    validated = false;
            //}
        }
        if (validated == false) {
            $('#vNewPassword').text('Password must contain at least one lower and upper case character and one number.');
            return false;
        } else {
            return true;
        }
    )};
 }
</script>

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