2

I'm trying to validate a form input value. The function below states is the value of the input is a number below 150, show error. Works as it should. However, I want to add to it. If the value contains ANYTHING other than a numeric value AND/OR is a value under 150, show error...

How can I modify?

if ($('.billboard-height').val() < 150) {
    $('.sb-billboardalert').fadeIn(600);
}
1
  • why dont you just prevent any input other than numeric, that way they cant press on anything but 0-9 Commented Mar 6, 2013 at 0:04

9 Answers 9

2

Since your more thorough validation should be on the server-side anyway, you could just use parseInt or parseFloat depending on what sort of value you are expecting. Then check if the result is actually a number and that it also meets your constraints:

var number = parseFloat($('.billboard-height').val()); // or parseInt depending on expected input
if (isNaN(number) || number < 150) {
    $('.sb-billboardalert').fadeIn(600);
}

EDIT:

Based on your comments, you are entering regex land. I gather you only ever want a natural number (and the way parseInt/parseFloat ignores trailing non-numeric characters like px, em, etc. is not ok). How about:

var val = $('.billboard-height').val();
var number = parseInt(val, 10);
if ( ! val.match(/^[0-9]{3,4}$/) || number < 150) {
    $('.sb-billboardalert').fadeIn(600);
}

This should only allow natural numbers 150-9999.

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

4 Comments

I like this! Clean and simple!
In short, the .billboard-height is a pixel value for the height...but I only want numerics to be entered through the text input, as the px is added separately. Your code prevents some typing in 460px for example, but the $('.sb-billboardalert').fadeIn(600); won't display. It only will IF the value is below 150
I want to prevent people from entering px, %, or em, etc in the text field.
@MikeBarwick - Not sure if SO automatically notifies you of edits but I added one that hopefully hits the spot.
2

I would suggest using regexes:

var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
   alert('I am a number');
   ...
}

Or with a single regex as per @Platinum Azure's suggestion:

var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
   alert('I am a number');
   ...
}    

ref: checking if number entered is a digit in jquery

1 Comment

Those regexes seem over-complicated... To test an int you can just make sure there is no match on this regex: [^0-9-].
1

Don't forget the radix parameter in parseInt():

if (parseInt($('.billboard-height').val(), 10) < 150) {

It's probably faster than using a regex. Regular expressions are not known for being fast, but they are very powerful. It might be overkill for this scenario.

Comments

0

You can try out HTML5's built in form validation:

<input type="number" min="150">

browser support is still pretty shakey though

Comments

0

Any value from an input or select will be a string in javascript. You need to use parseInt() to use operators like > or <. == can be used if you use it to compare to a string like if ($('.billboard-height').val() == "150")

Comments

0

Try parseInt and isNaN functions for check if value is number and less than 150:

var intVal = parseInt($('.billboard-height').val());
if(!isNaN(intVal)){ //not Number
    if (parseInt($('.billboard-height').val()) < 150) { //not less than 150
        $('.sb-billboardalert').fadeIn(600);
    }
}

Comments

0

If you need to support floating point numbers, you can check if a variable is valid using:

function isNumber (n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

var val = $('.billboard-height').val();
if (isNumber(val) && parseFloat(val) < 150) {
    $('.sb-billboardalert').fadeIn(600);
}

If you only need to support integers, use parseInt(n, 10), where 10 is the base to convert the string to.

var val = parseInt($('.billboard-height').val(), 10);
if (val && val < 150) {
    $('.sb-billboardalert').fadeIn(600);
}

Comments

0
// Displays an alert if s contains a non-numeric character.

function alertForNonNumeric(s) {
    var rgx = /[^0-9]/;
    if (s.search(rgx) !== -1) {
        alert("Input contains non-numeric characters!");
    }
}

JS Fiddle here

NOTE: If you want to check for negative ints as well, you can add a minus sign to the regex:

function alertForNonNumeric(s) {
    var rgx = /[^0-9-]/;
    if (s.search(rgx) !== -1) {
        alert(s + " contains non-numeric characters!");
    }
}

Comments

0

I use this solution, I find it quite ellegant - no alerts, user is effectively unable to enter non numeric characters.

This is jQuery example:

function digitsOnly(){
    // extract only numbers from input    
    var num_val = $('#only_numbers').val().match(/\d+/);
         $('#only_numbers').val(num_val);
    } 

Your html:

<input type="text" name="only_numbers" id="only_numbers" on oninput="digitsOnly();"/>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.