Skip to main content

Exercise 3: Improve Data Entry Routine

  1. Start Studio, and open the mydatent routine.

  2. Write the $$validName user-defined function.

    validName(name) PUBLIC ; validate a Name
        /* returns 0 for an invalid name and writes error message
           returns the unchanged name otherwise */
        {
        if (name?1u.l1","1u.l) {
            quit name }
        else {
            write !,"Last,First"
            quit 0
           }
        }
  3. Write the $$validPhone user-defined function. After verifying the phone number, add the default area code if necessary.

    validPhone(phone) PUBLIC ; validate a phone number
        /* returns 0 for invalid phone numbers and writes error message
           returns the valid phone number with default area code added 
           if necessary */
        {
        if (phone?.1(3n1"-")3n1"-"4n) {
            set:(phone?3n1"-"4n) phone = "617-" _ phone ; add default area code
            quit phone
           }
        else {
            write !, "###-###-#### or ###-####"
            quit 0
           }
        }
  4. Write the $$validDOB user-defined function. Make sure you disallow future dates.

    validDOB(date) PUBLIC ; validate a Date of Birth
        /* returns 0 for invalid dates and writes error message
           returns internal format for valid dates */
        {
        set convdate = $zdateh( date, 5,,,,,,, -1)
        if (convdate = -1) {
            write !,"Date in the past"
            quit 0 ; invalid date
           }
        elseif (convdate > $piece( $horolog, ",", 1)) {
            write !,"Date in the past"
            quit 0 ; invalid because it's in the future
           }
        else {
            quit convdate ; valid date
           }
        }
  5. Edit the prompt procedure. Use Do/While to cause prompts to repeat until the data is correct, using the three new “$$valid” user-defined functions.

    prompt() [name, phone, intdob]
      ; procedure for prompting
      {
        do {
            read !, "Name: ", name
            quit:(name = "")  ; user entered nothing
            set name = $$validName( name )
        }
        while name = 0
        quit:(name = "")  ; exit procedure
    
        do {
            read !, "Phone (617): ", phone
            set phone = $$validPhone( phone )
        }
        while phone = 0
    
        do {
            read !, "DOB: ", dob
            set intdob = $$validDOB( dob )
        }
        while intdob = 0
        write !!
      }
  6. Edit the display procedure. Add code to convert the date to the external format you like best.

    display() [name, phone, intdob]
        ; display the data
        {
        write !, "Name:", ?20, name
        write !, "Phone:", ?20, phone
        write !, "DOB:", ?20, $zdate( intdob, 2)
        write !!
        }
FeedbackOpens in a new tab