jQuery Validation custom validation adding no space validation

后端 未结 1 1864
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 01:30

I have a form where the user can update his name and last name. I use jQuery validation to validate the form. How can I validate if the user put spaces?

here\'s what i h

相关标签:
1条回答
  • 2021-02-07 01:58

    use this for your javascript code:

    $(document).ready(function() {
    
      jQuery.validator.addMethod("noSpace", function(value, element) { 
         return value.indexOf(" ") < 0 && value != ""; 
      }, "Space are not allowed");
    
      $("#myform").validate({
        errorLabelContainer: $("#error"),
        rules: {
          fname: { required: true, noSpace: true },
          lname: { required: true, noSpace: true }
        },
        messages: {
          fname: { required: 'Please enter your name' },
          lname : { required: "Please enter your last name" }
        }
      });
    
      $('#submit').click(function() {
        var valid = $("#myform").valid();
        if(!valid) {
          return false;
        }
        $.ajax({
          beforeSend: function() {
            // display loading message
          },
          type: "POST",
          url: 'save',
          data:  $('#formdata').serialize(),
          dataType: 'json',
          cache: false,
          success: function(result) {
            if(result.error) {
              // show error message
            }
            else {
              // redirect to another page
            }
          },
          error: function (response, desc, exception) {
            // show ajax error
          },
          complete: function() {
            // hide loading message
          }
        });
      });
    });
    
    0 讨论(0)
提交回复
热议问题