0

How to allow text and number but not allow special char in this input ?

in my code , it's will allow only number, i want to apply to allow text too,

How can i do that?

and can i user this function base on javascript ?

http://jsfiddle.net/mhgv0wt0/

<form action=# name=f1 id=f1 onsubmit="return false">
<input type=text name=t1 id=t1 value="" size=25 style="width:300px;"
 onkeypress="if(this.value.match(/\D/)) this.value=this.value.replace(/\D/g,'')"
 onkeyup   ="if(this.value.match(/\D/)) this.value=this.value.replace(/\D/g,'')"
>
</form>
1
  • Define “allow” (should the checks be made when entering characters, or upon submission?), “number” (is −3.14 a number?), and “text” (is “fiancé” text?). When you have exactly defined the problem, you have almost solved it. Commented Oct 2, 2014 at 14:15

2 Answers 2

1

Just add a pattern attribute:

<input pattern="^[a-zA-Z0-9\s]+$" type="text" />

DEMO

The above will do in most browsers. But you can fall back to jQuery using

$('input').keypress(function (e) {
    if (!/[a-zA-Z0-9\s]/.test(String.fromCharCode(e.which || e.keyCode))) {
        e.preventDefault();
    }
});

DEMO

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

4 Comments

This will only work in certain browsers. For older browser support you'll need javascript as described here
@SarahBourt be patient :)
you might want to use the whitespace character (\s)
jsfiddle.net/8qfz1dhh/1 it's ok , but i want to remove special char when keyup even
0

use jQuery. Also you might want to use the whitespace character (\s)

$('#t1').bind('keypress', function (event) {
    var regex = new RegExp("^[a-zA-Z0-9]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

try this fiddle

1 Comment

i can not insert special into input too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.