1

I'm using jquery validator alpha numeric rule but i want to allow space but right now the issue is when i give space it shows error, my main requirement is i don't want user to enter special characters ore symbols in text fields, my code is like this:

<form id="myform">
    <input type="text" name="field" />
    <br/>
    <input type="submit" />
</form>

Script:

$(document).ready(function () {
    
        $('#myform').validate({ // initialize the plugin
            rules: {
                field: {
                    required: true,
                    alphanumeric: true
                }
            },
            submitHandler: function (form) { // for demo
                alert('valid form submitted'); // for demo
                return false; // for demo
            }
        });
    
    });
Sparky
  • 98,165
  • 25
  • 199
  • 285
user3653474
  • 3,393
  • 6
  • 49
  • 135

1 Answers1

2

You can use custom validator method and specify your custom validation there.Whenever user clicked on submit button this will get called and will validate the input according to the rules defined in it .

In below code i have use regex to match user input . i.e :

^ : It represents start of string .
\w : It matches any word character (equal to [a-zA-Z0-9_])
(space or ) \s : It matches any space, tab or newline character.
$ : It represent end of string .
.test(value) :It match between a regular expression and a specified string and return true or false.

Demo code :

$(document).ready(function() {
  //add this custom methid
  $.validator.addMethod("alphanumeric", function(value, element) {
    //test user value with the regex
    return this.optional(element) || /^[\w ]+$/i.test(value);
  }, "Letters, numbers only please");

  $('#myform').validate({ // initialize the plugin
    rules: {
      field: {
        required: true,
        alphanumeric: true
      }
    },
    submitHandler: function(form) { // for demo
      alert('valid form submitted'); // for demo
      return false; // for demo
    }
  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js
"></script>
<form id="myform">
  <input type="text" name="field" />
  <br/>
  <input type="submit" />
</form>
Swati
  • 28,069
  • 4
  • 21
  • 41