Stick it to THE MAN
Stick it to THE MAN

Reputation: 5721

Javascript function involving use of regex

I am allowing a user to enter dimensions of a box through form fields. the permissible values are:

  1. positive integers
  2. must end with px or %

Sample valid numbers are 300px or 70%

In addition, I want to place some extra validation logic:

If entered value is in percentage, then the number must lie in the range 0 > x <=100

If the number entered is in px, I want to be able to check against hard coded min and max values.

My regex knowledge is pretty scanty, as I havent used it for many years.

I am think of writing a set of helper function like this:

// returns true if value ends in px or % [with no spaces], false otherwise
function is_scale_valid(value){
}

//returns 'px', '%' or undefined 
function get_scale_type(value){
}

// called after is_scale_valid, to ensure we are dealing with
// a +ve integer that falls in desired range. This function 
// strips away the 'scale' part of the value and only looks 
// at the number
function is_valid_number(value, scaletype, valid_min, valid_max){
}

can anyone help me fill out these helper functions?

Upvotes: 1

Views: 103

Answers (1)

cletus
cletus

Reputation: 625485

The regular expression you want is:

var r = new RegExp("^\\s*(\\d+(?:\\.\\d+)?)\\s*(px|%)?\\s*$");

This expression means:

  • Allow leading and trailing white space (\s);
  • The number is one or more digits optionally followed by a period and one or more digits;
  • The units can be "px", "%" or left out.

You'll need to manually check the inputted number from that.

var match = r.exec("93px");
var number = parseFloat(match[1]);
var symbol = match[2];
if (symbol == "px") {
  // validate number as a pixel
} else if (symbol == "%") {
  // evaluate as percentage
} else {
  // no symbol was entered
}

Upvotes: 2

Related Questions