jquery form validate not allow space for username field?

后端 未结 7 1185
别那么骄傲
别那么骄傲 2020-12-17 14:43

I have used http://bassistance.de/jquery-plugins/jquery-plugin-validation/

my form validate :

$(\"#form_person\").validate({
    rules: {


        u         


        
相关标签:
7条回答
  • 2020-12-17 14:53

    I used the answer of @Reigel but it didn't work for me.

    I have change his example like this :

      $(document).ready(function(){
    
        jQuery.validator.addMethod("noSpace", function(value, element) { 
          return value == '' || value.trim().length != 0;  
        }, "No space please and don't leave it empty");
    
    
        $("form").validate({
           rules: {
              name: {
                  noSpace: true
              }
           }
        });
    
    
      })
    

    In my opinion noSpace isn't responsible to verify empty TextBox(Input). It is responsible to check value if some things was entered.

    And it will be a good idea if you use jQuery.validator.addMethod... in other JS file and add this JS file to your master page or some things like that.

    0 讨论(0)
  • 2020-12-17 14:55

    Take a look to aditional methods, there is a nowhitespace rule.

    0 讨论(0)
  • 2020-12-17 15:03
    $.validator.addMethod("validUsername", function (value, element) {
        return /^[a-zA-Z0-9_.-]+$/.test(value);
    }, "Please enter a valid username");
    

    Add this method in validation

    $("form").validate({
       rules: {
          name: {
              validUsername: true
          }
       }
    });
    
    0 讨论(0)
  • 2020-12-17 15:05

    example like this :

       $('#username').keypress(function( e ) {
           if(e.which === 32) 
             return false;
        });
    
    0 讨论(0)
  • 2020-12-17 15:14

    Since jquery-validation 1.15.0 a cleaner approach is to use the normalizer callback:

    $( "#myform" ).validate( {
      rules: {
        field: {
          required: true,
          normalizer: function( value ) {
            return $.trim( value );
          }
        }
      }
    } );
    

    The normalizer (immutably) transforms the value before the validation takes place.

    See the Normalizer Docs for more details.

    0 讨论(0)
  • 2020-12-17 15:17

    I just add the onfocusout event and its automatically Trim all the form fields and also if the user will enter only spaces (white-spaces) it will remove them and will show the field required message:

    onfocusout: function (element, event) {
    
        //Get Objects
        $element = $(element);
    
        //Remove whitespace
        if ( $element.is(':input') && !$element.is(':password') ) {
            $element.val($.trim($element.val()));
        }
    },
    

    Its working also when the user submit the form directly because when he click the submit button the event is triggered.

    0 讨论(0)
提交回复
热议问题