Friday, September 21, 2018

Using regular expressions on field validations

A NetSuite user would like to validate user input on specific fields. For example, he created a Transaction Body Field which should have a value based on the following conditions:
 
a. Starts with an alphabetical character from capital A - H (both inclusive)
b. Followed by exactly 10 Numberic Digits
c. The first three digits should be less than 300 i.e. Valid values are 123, 255, 299. Invalid: 300, 301, 888 etc.
d. The remaining 7 digits can be any values. But it should have total 10 digits.
e. The field can have a null value

Doing the scenario given above using a long series of if-else statements would be hard and time costly. One needs to use regular expressions to do this the easy way and the right way. Below is a sample code to do the field input validation:

function validateInput(type, name) {
if (name == 'custbody_account_number') {
  var regx = /^[A-H][0-2]\d{9}$/;
  var accountNumber = nlapiGetFieldValue('custbody_account_number');
  
  if(accountNumber == '' || accountNumber == null)
   return true;
  
  if (!regx.test(accountNumber)) {
   alert('Please enter a valid account number');
   return false;
  }
  else {
   return true;
  }
}
return true;
}

 

Note: Deploy code as a Client Side script on the Validate Field function.

No comments:

Post a Comment