0

I have TextBox on my page. I want to validating this textbox.

The rules are :

  1. TextBox should not get more than 20 chars
  2. Only aphanumeric and chars like / - # & ^ spaces to be allowed

how to do using jquery in best way

2 Answers 2

1

The appropriate regex would be:

^[a-zA-Z0-9/#&^\- ]{0,20}$

Ask yourself if A-Z is the right thing. You may be wanting to allow more than that (accented characters for example).

Use the JavaScript Unicode Block Range Creator to accommodate the regex for a broader set of allowed input. Check allowed characters with with the handy Javascript RegExp Unicode Character Class Tester.

As always, double check form values on the server side. Relying on JavaScript to do all input checking is dangerous.

For jQuery, have a look at the Valitator plugin, and use code along the lines of:

$.validator.addMethod(
  "yourFormField", 
  function(value) { 
    return /^[a-zA-Z0-9/#&^\- ]{0,20}$/.test(value); 
  }, 
  "Please enter a valid value."
);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanku. Is there possible to check validation as user types. Can I do without using plugin, just my own jquery?
Of course. The plugin was just a suggestion. Use the regex any way you like. However, I would not recommend checking every character as it is typed, but doing a single check when the form field loses focus.
Plz tell how to do validation without plugin..full example is very good..sorry about it as my first day at jquery
I want that if user types invalid char and submits form or moves away from textbox, message should fire. How to do. plz give complete example
No offense, but I would say you try it first, and come back to Stack Overflow with a specific problem you are encountering. "plz give me the codez" doesn't cut it, at least not for me.
0

^[a-zA-Z0-9/#&^- ]{0,20}$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.