Fahad Hasan
Fahad Hasan

Reputation: 10506

Input field to only accept a specific number

I have created a form and now I want to add an input field inside it which would only accept a specific number i.e. the digit '4'. This is more like a spam check where the user is asked that 'What is the answer of 1+3?' and then he/she would've to enter the digit '4', in the input field, in order for the form to get processed. This could also work in a manner that if any other number is entered inside the input field and the form is submitted, a pop up window is fired explaining the error.

I have created a jsfiddle which only accepts the digit 4 but sadly it is allow accepting 'full stops'.

HTML:

<input id="humancheck" type="text" maxlength="1" name="humancheck" required />

Javascript:

jQuery('#humancheck').keyup(function () { 
    this.value = this.value.replace(/[^4-4\.]/g,'');
});

Upvotes: 0

Views: 1669

Answers (2)

Epiphany
Epiphany

Reputation: 1894

I know this post is a bit moldy, so I thought I might bring it a bit more current.

First, you should not use the 'keyup' for the event trigger, as it is to processor intensive. Imagine if you were wanting to match a number with more than one digit, and you can see how the 'keyup' becomes problematic.

Using the 'blur' event is a better trigger, as it checks the number value after the user has finished entering a number into the form field.

If I am understanding the OP, then why use a regex at all for a simple match? Instead, this is one way I would write your function (for jQuery 1.11.0+). It also makes an additional check to assure the entry is indeed a number as well.

$('#humancheck').blur( function(){ 
  if (isNaN(this.value)) alert('Not a Number');
  if (this.value != 4) alert('Incorrect Number');
});

Upvotes: 0

Jordan Scales
Jordan Scales

Reputation: 2717

Your regex should only be replacing [^4] (any character which is not 4). I'm not sure why you have also included -4 (range) and \. ('.' character).

Just to note, securing on keyup doesn't help much. Anyone can fire up webkit inspector and place a 3 in there manually. If this is just a fun experiment, though, that's cool too :)

Upvotes: 2

Related Questions