1

I'm trying to use a pattern on an html5 input text. This textbox should allow all the characters and number, both lowercase and uppercase and a maxLenght of 16, but NOT the special characters.

i tried this pattern, but it doesn't work (if i miss some character fell free to pointing it out):

[^!\£$%&/()=?^*§#@_:,;.-+-/|]*

HTML

<form>
<INPUT TYPE="TEXT"
       pattern="[^!\£$%&/()=?^*§#@_:,;.-+-/|]*" maxLenght='16' value="">
<input type="submit">
</form>

<span class="result"></span>

JavaScript

$("form").on("submit", function (evt){
  $(".result").html('ok');
  evt.preventDefault;
})

Example here: http://codepen.io/anon/pen/avNKMm?editors=101

any help would be really appreciated.

Thanks a lot.

3
  • Can the field be empty? Do you really want to allow spaces/tabs, too? Commented Sep 18, 2015 at 9:47
  • Yes, spaces and tabs are fine Commented Sep 18, 2015 at 9:48
  • 1
    thanks @stribizhev i edited my question with the snippet in the body Commented Sep 18, 2015 at 10:25

2 Answers 2

3

Use regex as

[a-zA-Z0-9\s]{0,16}

Demo

$("form").on("submit", function(evt) {
  $(".result").html('ok');
  evt.preventDefault();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <INPUT TYPE="TEXT" pattern="[a-zA-Z0-9\s]{0,16}" maxLength='16' value="">
  <input type="submit">
</form>

<span class="result"></span>

Explanation here

Regular expression visualization

Sign up to request clarification or add additional context in comments.

1 Comment

Try just pattern="[A-Za-z]" as the pattern only shows allowed characters
1

Note that you have a typo in maxLenght. Change to maxlength so that it could work correctly.

You should try to use a whitelist approach rather than a blacklist one. Define what you allow:

all the characters and number, both lowercase and uppercase

That means, [a-zA-Z\d] and

and a maxLenght of 16

You should be aware of the fact that pattern attribute regex is anchored by default, so we can safely use {1,16} (a limiting quantifier matching 1 to 16 occurrences of the preceding subpattern).

To disallow empty value, use required attribute.

So, I would recommend:

<INPUT TYPE="TEXT"
   pattern="[a-zA-Z\d\s]{1,16}" required maxlength='16' value="">
             ^^^^^^^^^^^^^^^^^  ^^^^^^^^       ^^^

Updated PEN

$("form").on("submit", function (evt){
  $(".result").html('ok');
  evt.preventDefault;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<INPUT TYPE="TEXT"
       pattern="[a-zA-Z\d\s]{1,16}" required maxlength='16' value="">
<input type="submit">
</form>

<span class="result"></span>

2 Comments

Isn't it maxlength, not maxLength?

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.