tags:

views:

90

answers:

3

Hi!

I have this javascript function that block special characters...

function validaTexto(texto)
{
    !(/^[A-zÑñ0-9]*$/i).test(texto.value) ? texto.value = texto.value.replace(/[^A-zÑñ0-9]/ig, '') : null;
}

The problem is that this function doesn't allow me to type blank spaces... how can I customize this function to allow me some other things, such as blank spaces, "," , "." , ";" and so on?

Thanks!!

+1  A: 
function validaTexto(texto) {
    texto.value.replace(/[^A-z0-9 ,\.;]/ig, '');
}

Referenes (with examples):

Koistya Navin
there's an error in the first regex. it's checking whether the entire string consists of the allowable characters, and if it does, then remove the ones which aren't allowable. also, the special "ñ" character isn't checked for here.
nickf
+1  A: 

change the regex to this:

!(/[^A-zÑñ0-9 ,\.;]*$/i)

also, the function is quite redundant in that it checks the string twice, basically saying "Does the string contain any of these characters? Yes? Ok, so search the string for these same characters and remove them. Just change it to this:

function validaTexto(texto) {
    texto.value.replace(/[^a-zñ0-9 ,\.;]/ig, '');
}
nickf
A: 

Read this post:

http://stackoverflow.com/questions/576196/regular-expression-allow-letters-numbers-and-spaces-with-at-least-one-letter

With a bit of effort, you should be able to modify your regex to do what you need.

karim79