site logo

Continental Number Validation

How to validate numbers in web form with reference to national conventions and some other problems of number validation are described in this article. Number validation in browser is performed to prevent from errors on server at string to numeric data type conversion and errors from attempt to save incorrect data type into the database.

Numeric data, which are entered to the textbox of web form, as well as form data which are submited to server are always string data type. As valid numeric data we consider such string, which client and server evaluate as valid number and in addition is in line with data type of database column where data are to be saved.

US notation of float number use as separator of decimal part of number character dot, while continental conventions prescribe to use character comma there. Character comma can be used in Anglo-American countries for separation of groups digit places (thousands). Continental conventions for this case employ character space. JavaScript in functions for type casting from strings to numeric values always requires using decimal dot as Decimal separator and no Thousands separator.

Correct number validation in browser with regard to national conventions of application is necessary, but not sufficient. Request form variables which carry real number numeric string have to be unified on server, to contain proper Decimal Separator. This decimal separator depends on current national environment of server programming language and database setting. Numerical range of integers according to data type of database should be tested in order to avoid overflow errors. Keep in mind, that saving big positive integer number sometimes overflows to the range of negative numbers.

Because some desktop programs require to use decimal point (dot), while others require decimal comma, users are often confused which decimal separator to use. The best practise may be to allow both and for internal calculation and validation unify decimal separator according to system needs. Type of decimal separator on numeric keypad is automatically set by switching between English and some national languages.

number type value result
integer number
float number
any number

Test form and number validation scripts

Type some numbers to the mini-form and click button validate to start validation script. JavaScript functions evaluates numerical data and notify result in right column of form.

At numbers validation procedure is following: input fields, (always type of string) are converted to type numeric by the help of two different method and both numerical values are compared. When values are not identical, content of input field is not number.

Some validation methods use one conversion to type numeric, followed by conversion back to type string. Result should be equal to initial text string. Such style of validation operate untill, somebody leave space (white character) in front of, or behind the number. Because such a space is not visible in textbox, it is very hard to recognize source of error. There have been yet another methods for validation numbers e.g. by the help of regular expression, or by help of function isNaN(). These are not described here.


// ---------- integer number validation -----------
function isInteger(value) {
  if(value == "") return false;
  if(parseInt(value, 10) != (value*1)) return false;
  return true;
}

First sample code for conversion text string to numeric type is by the help of function parseInt(). Conversion is terminated at the end of string, or at match of non-numerical character. Second parameter in function parseInt() determines base in which conversion proceeds. Skiped base parameter can sometimes cause incorrect validation in different browsers. E.g. numbers beginning with zero may be treated as octal base, leading 0x as hexadecimal base.

Further simple arithmetic operation is executed. That operation does not change value, but performs type casting to numeric type. It is possible to use multiplication by one, division by one,or subtraction zero. Be care, it is not possible to add zero. Operation plus is interpreted as string concatenation, in this case would mean multiplication by ten. Both results, now data type numeric, are compared. As far as are equal, text parameter is convertible to numerical data and can be regarded as valid number.


// ---------- float number validation -------------
function isFloat(value) {
  if(value == "") return false;
  value = value.replace(/,/, '.');
  if(parseFloat(value) != (value*1)) return false;
  return true;
}

The second code sample validates floating point number. Function allow both scientific and standard style of notation. First test, whether string is not empty. By that possible JavaScript conversion errors in older browsers are avoided. Run time JavaScript error in IE causes break of validation routine and form is sent off as if it had been valid.

The second line of script unifies decimal separator to decimal point. According to continental conventions, comma as decimal separator is required, therefore decimal comma is replaced by decimal point. Type casting by JavaScript function parseFloat() expects decimal point in string. Original string in textbox stay unchanged and in original format is also submited to server as part of form data. Similar unification of decimal separator have to be performed also on server, this time with reference to convention of database.

Further function proceeds in the same way as in previous example with only difference of using casting function parseFloat(). This function does not require base parameter, casting proceeds always in decimal base.


// ---------- any number validation -------------
function isNumber(value) {
  if(value == "") return false;
  value = value.replace(/ /gi, "");
  value = value.replace(/,/, '.');
  oneDeci = false;
  for (var i = 0; i < value.length; i++) {
    var oneChar = value.charAt(i);
    if (i == 0 && oneChar == "-") {
      continue;
    }
    if (oneChar == "." && !oneDeci) {
      oneDeci = true;
      continue
    }
    if (oneChar < "0" || oneChar > "9") {
      return false
    }
  }
  return true;
}

Last example is a bit different way of numeric data validation. Instead of conversion to numeric data type, allowed characters are tested. The second line of code deletes all spaces from input string (thousands separators, leading, closing space). Next line performs potential replacement of decimal comma for point. In the fourth line of code occurrence of decimal separator flag is reset.

Adapted string is passed character by character for test. First character can be negative sign. Further test is decimal point occurrence, which may appear in string only once. All else characters can be digits only.

It is possible to use space as thousands separator and either decimal point or comma in input string. It is not possible to use plus sign for positive numbers, or US thousands separator by comma. Code example fits as basis for experiments with modification of validation function. There are often specific requirements of formating input string numbers (fixed number of decimal digits, positive numbers only, specified range of number). In such a case, validation function needs to be modified according to request.

It is possible to replace the last code example by built-in function IsNumeric() in VBScript in similar way as was described in previous article. I do not advise to use VBScript for validation functions in browser, but on server side this old programing language is quite efficient.

Number context validation

When all numbers in form are valid, that does not mean the form is filled in correctly. One number can be in relation or in context with other number(s). Lets have two input fields for netto and brutto weight as example. Brutto weight have to be higher, or the same as netto weight. If not, input values were replaceed. Intranet working with production, technological or laboratory data forms has quite a lot of such context validation scripts.

I demonstrate principle of context validation based on example of decimal numbers comparition. Suppose two input textboxes containing valid values of weight. Both input fields were validated by function isFloat() described earlier.


// ---------- compare decimal numbers -------------
function compareFloat(num1, num2) {
  brutto = num1.replace(/,/, '.');
  netto  = num2.replace(/,/, '.');
  if(parseFloat(netto) > parseFloat(brutto)) return false;
  return true;
}

When textbox contains decimal number entered in national conventions, that means contains decimal comma instead of decimal point, then function parseFloat() cut off decimal part of number without warning. Therefore first of all decimal comma have to be replaced by decimal point. Such strings are correct for processing in JavaScript. Numeric input fields can contain either decimal comma or decimal point as decimal separator, but internal strings representation in validation function are correct for calculation.

Some JavaScript operators provide automatic type casting to numeric type (multiplication, division). Other operators (addition, comparison) do not provide type casting and result depends on operands type. Numerical comparition is required in this example therefore type casting to numeric type have to be done. Keep in mind the requirement of type casting when write context number validation.

updated 22.01.2010