RSM
RSM

Reputation: 15108

Detecting whether user input contains a forbidden character in JavaScript

I have a text box that is going to be validated in JavaScript upon click on the submit button.

Only the character 0-9 and a-f and A-F are allowed.

So g-z and G-Z as well as other characters such as punctuation or not allowed.

The code I have so far is:

function validate_form ( )
{
    valid = true;

    if ( document.form.input.value == [a-zA-Z_,.:\|] )
    {
        alert ( "You can only enter either 0-9 or A-F. Please try again." );
        valid = false;
    }

    return valid;
}

Which doesn't seem to work.

I'm new to JavaScript so can any one please give me a hint as to where I'm going wrong?

Upvotes: 1

Views: 769

Answers (4)

brymck
brymck

Reputation: 7663

We can actually clean this code up a lot. There's no need to keep track of valid as test() will provide us with the true or false value we're looking for. It's also a good deal easier in your case to keep a whitelist of acceptable characters rather than a blacklist. That is, we know every character we want, but can't possibly specify every character we don't want.

function validate_form() {
  return /^[a-fA-F0-9]+$/.test(document.form.input.value);
}

Note that you can also use this to do a pre-check:

document.form.input.onkeyup = function() {
  if (!validate_form()) {
    alert("You can only enter either 0-9 or A-F. Please try again.");
  }
};

Upvotes: 3

Jason Gennaro
Jason Gennaro

Reputation: 34855

You could do something like this

$('input').keyup(function(){
    var charac = /[g-zG-Z;:,.|_]/;
    var result = charac.test($(this).val());
    if(result == true){
        alert('You can only enter either 0-9 or A-F. Please try again.');
    }
})

http://jsfiddle.net/jasongennaro/GTQPv/1/

Upvotes: 0

Gabi Purcaru
Gabi Purcaru

Reputation: 31524

the syntax is /^[a-zA-Z_,.:\|]+$/.test(document.form.input.value). Notice the ^ and $: without them, the test will pass even for strings that have only at least one allowed character.

Upvotes: 2

Saeed Neamati
Saeed Neamati

Reputation: 35822

The best way for validation is to not let the user, enter wrong character. Use this code (this is the jQuery version, but you can also convert it easily to JavaScript):

 $('#inputFiledId').keyup(function(e){
     // checking the e.keyCode here, if it's not acceptable, the return false (which prevents the character from being entered into the input box), otherwise do nothing here.
 });

This is called pre-check. Please consider that you whatever you do in client-side, you should always check the values at the server also (have server-side validation) as there are multiple hacks around, like form-spoofing.

Upvotes: 0

Related Questions