Input Validation of comma separated values

Hello all,

I am working on a script and have the first part solved of numerical input validation. Below the code validates that the input is a numerical value between 100 and 1000. If not, it errors out. Now I need to be able to read values separated by a comma. For example, instead of my input being let's say 105, I'd like for the input validated to be more like 105,106,500. How can I achieve this masters of scripting?

Current code for custom function:

get_info_check ()
{
echo
echo "Which INFO check would you like to run?"
echo "The valid range is 100-999."
print -n "Enter INFO number : "
read INFO_CHK
#INPUT VALIDATION HERE!!!
if [[ "$INFO_CHK" != +([0-9]) ]]
  then
      echo
      echo "ERROR: You must enter a valid number!!"
      get_info_check
elif [ "$INFO_CHK" -ge 100 -a "$INFO_CHK" -le 999 ]
  then
     echo "GOOD JOB!!!"
else
     echo
     echo "ERROR: Valid range is 100-999!!"
     get_info_check
fi
}

Here is one way of having the input parameters separated by comma:

#!/usr/bin/ksh
IFS=','
for mParm in $@
do
  echo "mParm = <$mParm>"
done
1 Like

Thanks for your reply. I guess one thing I forgot to mention above is that I only want the input line, because it will be passed off to another script to decide what to do with the input. For example, I want it to echo "GOOD JOB!!!' only when the criteria are met, and error out if any of the comma separated fields are not valid.

#!/bin/sh

read INFO_CHK

echo "$INFO_CHK" | sed 's/,/\n/g' | while read a; do
    echo "$a"
# Do whatever you want with "$a"
done

The idea here is to convert ,(commas) with \n (new line) so we can read every record the same way we'd do with a file. Hope it will help you

1 Like

I see, but will it keep the input such as 105,106,500 in that format, so it can be passed off as an option to another script?

INFO_CHK will keep '105,106,500'
While in the 'while' loop, a will be 105, then 106, then 500, so you can check inputs separately
After the 'done', INFO_CHK will still hold '105,106,500'
Hope it's clear enough :o

1 Like