Zan
Zan

Reputation: 114

Special Characters Validation

I have a JQuery code like this:

// Validation to avoid non alphanumeric characters from being typed
function alphanumeric(eventSource) {
    var numaric = eventSource.val();
    for (var j = 0; j < numaric.length; j++) {
        var alphaa = numaric.charAt(j);
        var hh = alphaa.charCodeAt(0);
        // If the value contains non alphanumeric characters
        if (!((hh > 47 && hh < 58) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123))) {
            eventSource.val(numaric.substring(0, j) + numaric.substring(j + 1,  numaric.length));
        }
    }
}

I am trying to validate the special characters of a text box input. But somehow, it also validates the space (space bar on keyboard), which the char code is 32. Advice please, thanks.

Upvotes: 0

Views: 1541

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this code

var regtest = 'dfdsfdsf23424';
var letters = /^[a-zA-Z0-9]+$/;    
var result = letters.test(regtest );
console.log(result);​//true

regtest = 'dfdsfdsf 23424';
result = letters.test(regtest );
console.log(result);​//false

Test the fiddle http://jsfiddle.net/Stw2Y/

For you function you will avoiding the special characters then try this

var letters = /^[a-zA-Z0-9]+$/;    
function alphanumeric(eventSource) {
    var numaric = eventSource.val();
    var str='';
    for (var j = 0; j < numaric.length; j++) {
        var alphaa = numaric.charAt(j);
        // If the value contains non alphanumeric characters
        if(letters.test(alphaa))
        {
             str+=alphaa;
        }
    }
    eventSource.val(str);   
}

Test here http://jsfiddle.net/Stw2Y/1/

Upvotes: 1

Iswanto San
Iswanto San

Reputation: 18569

Try this :

        function alphanumeric(eventSource) {
            var numaric = eventSource.val();
            for (var j = 0; j < numaric.length; j++) {
                var alphaa = numaric.charAt(j);
                var hh = String.charCodeAt(alphaa);                
                // If the value contains non alphanumeric characters
                if (hh != 32 && !((hh > 47 && hh < 58) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123))) {
                    eventSource.val(numaric.substring(0, j) + numaric.substring(j + 1, numaric.length));
                }
            }
        }       

Upvotes: 1

Related Questions