Improving this validate function

Hi guys, I use this function which was provided to me by someone at this site. It works perfectly for validating a users input option against allowed options..

example:

validateInput "1" "1 3 4 5" would return 0 (success)

function validateInput {
 input=$1
 allowedInput=$2
 
 for allowedOption in ${allowedInput}
 do
  if [ ${input} -eq ${allowedOption} ]
  then
   return 0
  fi
 done
 
 return 1
}

but now we allow users to enter more than 1 number and so this validate needs to be improved

validateInput "16" "1 3 4 5" this should return fail (1) as 6 is not in the allowedInput string.. currently the function return success because "1" is in the allowedInput string.. but I somehow need it to verify all the numbers in the first parameter

any ideas guys?

Well, now you need to validate the number of arguments, and validate each one separately.

validateInputs(){

 inputs=$1
 allowedInput=$2
 min_args=$3
 max_args=$4
 arg_ct=0
 inval_args=""

 for input in $inputs qzzq
 do
  if [ $input = qzzq ]
  then
   break
  fi

  for allowedOption in ${allowedInput}
  do
   if [ ${input} -eq ${allowedOption} ]
   then
    inval_args="$inval_args $input"
   fi
  done
  (( $arg_ct += 1 ))
 done

 if [ "$inval_args" != "" ]
 then
  echo "Invalid:$inval_args" >/dev/tty
  return 1
 fi

 if (( $arg_ct > $max_args || $arg_ct < $min_args ))
 then
  return 2
 fi

 return 0
}
$
$
$ cat -n f38
     1  #!/usr/bin/bash
     2  x=$1
     3  y=$2
     4  i=0
     5  while [ $i -lt ${#x} ]; do
     6    d=${x:$i:1}
     7    if ! [[ " $y " =~ " $d " ]]
     8    then
     9      echo "$d does not exist in $y"
    10      return 1
    11    fi
    12    i=`expr $i + 1`
    13  done
    14  echo "$x exists in $y"
    15  return 0
$
$
$ . f38 "1" "1 2 3 4"
1 exists in 1 2 3 4
$
$
$ . f38 "123" "1 2 3 4"
123 exists in 1 2 3 4
$
$
$ . f38 "0123" "1 2 3 4"
0 does not exist in 1 2 3 4
$
$
$ . f38 "1236" "1 2 3 4"
6 does not exist in 1 2 3 4
$
$
$ . f38 "1237" "1 2 3 77 4"
7 does not exist in 1 2 3 77 4
$
$

tyler_durden

And another one:

validateInput() {
  input=$1 allowedInput=$2
  while [ -n "$input" ]; do
  c=${input%${input#?}} input=${input#$c}
    case $allowedInput in
      ( *$c* )          ;;
      (   *  ) return 1 ;;
    esac
  done
  }

You want to be able to validate any word in a space delimited list, not every byte, right?

You might change your input validation to a case string, somewhat more varsatile with | (or), [abc] (list of char) and such:

#!/usr/bin/ksh

valInp(){

for i in $1 qzzq
do
 bad_args=""

 case "$i"  in
 (qzzq)
   ;;
 ($2)
   ;;
 (*)
   bad_args="$bad_args $i"
   ;;
 esac
done

if [ "$bad_args" != "" ]
then
 return 1
fi
}

Using a grep -E regex-pattern would be even more powerful.

#!/usr/bin/ksh

valInp(){

bad_args=""

echo $1 | tr ' ' '\12' | grep -Ev "$2" | while read bad
do
 bad_args="$bad_args $bad"
done

if [ "$bad_args" != "" ]
then
 return 1
fi
}