edoceo

JavaScript Data Validation

// input validation functions, cast to right type or erase
function to_date(elem)
{
  //var re1 = /^(0?[1-9]|1[012])([\-\/])(0?[1-9]|[12][0-9]|3[01])\2((19|20)\d\d)$/; // mm/dd/yyyy with - or /
  //if (re1.test(elem.value)) return to_type_success(elem);

  var m = null;
  // fix 'yyyy/mm/dd with - or /' to 'mm/dd/yyyy'
  var re = /^((19|20)\d\d)([\-\/]?)(0?[1-9]|1[012])\3(0?[1-9]|[12][0-9]|3[01])$/; //
  if (re.test(elem.value))
  {
    m = re.exec(elem.value);
    elem.value = m[4] + '/' + m[5] + '/' + m[1];
    return to_type_success(elem);
  }

  // Fix mmddyy or mm/dd/yy or mm-dd-yy to mm/dd/yyyy
  var re = /^(0?[1-9]|1[012])([\-\/]?)(0?[1-9]|[12][0-9]|3[01])\2(((19|20)\d\d|\d\d))$/;
  if (re.test(elem.value))
  {
    m = re.exec(elem.value);
    elem.value = m[1] + '/' + m[3] + '/';
    if (m[4].length==4) elem.value+= m[4];
    else elem.value+= (m[4] > 59 ? '19' + m[4] : '20' + m[4]);
  }

  var dt = new Date(elem.value);
  if (dt.toString() != 'Invalid Date')
  {
    elem.value = (dt.getMonth() + 1) + '/' + dt.getDate() + '/' + dt.getFullYear();
    return to_type_success(elem);
  }
  to_type_error(elem);
}

// func: to_email(elem,r) - converts 'elem' text into email address, blank's on error
function to_email(elem,r)
{
  var re = /^[a-zA-Z0-9_\.\-]+\@[a-zA-Z0-9\-]+\.[a-zA-Z0-9]{2,4}$/;
  if ( ((r) || (elem.value)) && (!re.test(elem.value))) to_type_error(elem);
  else to_type_success(elem);
}

// func: to_number(elem,s,p) ensures that $elem is in right $s (scale) and $p (precision)
function to_number(elem,s,p)
{
  var re = null;
  re = /\/|\*|\-|\+/;
  if (re.test(elem.value))
  {
    var x = eval(elem.value);
    if (x) elem.value = x;
  }
  
  if (!p) re = /^[0-9]+$/; // No precision is integers only
  else re = new RegExp('^([0-9]+\.?[0-9]*|\.[0-9]+)$'); // Floating point
  if (!re.test(elem.value)) to_type_error(elem);
  else to_type_success(elem);
}

// func: to_url(elem) - ensures 'elem' is an url
function to_url(elem)
{
  var re = new RegExp("^(http|https|ftp):\/\/(%[[:digit:]A-Fa-f][[:digit:]A-Fa-f]|[-_.!~*';/?:@&=+$,[:alnum:])+");
  var re = new RegExp("^(http|https|ftp)://");
  if (!re.test(elem.value)) to_type_error(elem);
  else to_type_success(elem);
}

function to_type_error(elem) { elem.style.border = '1px solid #f00'; }
function to_type_success(elem) { elem.style.border = '1px solid #333'; }

Loading Comments from Disqus...