Home > database >  Validate Input in yyyy/mm/dd Format Using C
Validate Input in yyyy/mm/dd Format Using C

Time:12-10

I want to check if the the buffer contains input that follows yyyy/mm/dd format. The issue I am having is figuring out how to check if there are '/' in the input.

Here is some sample code of what I had before

bool age_is_valid(const char* buffer){
    if (buffer == NULL) 
        return false;
    const int len = strnlen(buffer, 1024);
    int i;
    for (i = 0; i < len; i  ) {
        // return true if the buffer contains any alphabetical characters or spaces
        if (isalpha(buffer[i]) && isspace(buffer[i])) 
            return false;
    }

    return true;
}

I have tried changing the if statement to:

if (isalpha(buffer[i]) && isspace(buffer[i]) && !buffer[4] == '/' && !buffer[7] == '/') 
        return false;

This would check if the 5th and 8th elements of the buffer are '/', however, it does not work. I have also tried using isupper() and islower() rather than isalpha(), but still no luck.

CodePudding user response:

To check for yyyy/mm/dd, code could pedantically apply sscanf().

// scanf for 1 and only 1 digit character. Do not save.
#define D10 "%*1[0-9]"

bool age_is_valid(const char* buffer){
  if (buffer == NULL) return false;  // Invalid argument

  int n = 0;
  sscanf(buffer, D10 D10 D10 D10 "/" D10 D10 "/" D10 D10 "%n", &n);
  // If scan incomplete or junk at the end ...
  if (n == 0 || buffer[n]) return false;  // Format error

  int y,m,d;
  sscanf(buffer, "%d/%d/%d", &y, &m, &d);
  if ((y < YEAR_MIN || y > YEAR_MAX) ||
      (m < 1 || m > 12) ||
      (d < 1 || d > dom(y,m)) return false;  // Range error
  return true;
}

A more efficient test would use a series of isdigit() calls.

CodePudding user response:

A simple solution to your problem would be to iterate over each character of the buffer and do a separate check for the 5th and 8th character:

bool date_is_valid(const char* buffer){
    if (buffer == NULL){
        return false;
    }

    const int len = strlen(buffer);
    
    // check number of characters - yyyy/mm/dd is 10 chars
    if(len != 10){
        return false;
    }

    int i;
    for (i = 0; i < len; i  ){
        // for 5th and 8th character check if they are equal to '/'
        if(i == 4 || i == 7){
            if(buffer[i] != '/'){
                return false;
            }
        }
        // for all other characters check if they are valid digits
        else{
            if (!isdigit((unsigned char) buffer[i])){
                 return false;
            }
        }
    }
    return true;
}

Note that this kind of test would not validate if date values are in correct ranges.

  •  Tags:  
  • c
  • Related