1

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?

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.