Cash-
Cash-

Reputation: 67

How do I validate a phone number (Not US) with a efficient way?

so I am doing my assignment and it requires me to do validate the phone number.

This is the phone number's format. Example phone number: 012-7418521

XXX-XXXXXXX. Where the X must be digits and the format must include a '-' "Dash" on the 4th character and the total maximum characters is 11 including the "Dash".

Edit: I forgot 1 more thing, the first digit of the phone number or format must be a '0' zero digit where I forgot to validate it in my code.

My question is, is there any other efficient, simple and short way of validating the phone number format like using a loop or other methods that could be helpful.

This is my current way of validating at the moment. As I can't figure it out how to use a for loop to do it.

Question: Is my way considered efficient? I do not think so. By the way, I am using a function to validate it where I pass the array to the function and once it validates successfully it returns 1 otherwise 0.

Note: I am new to the coding world by the way.

int validateContact(char contact[]) {

    if (contact[3] == '-' && strlen(contact) == 11 && isdigit(contact[0]) > 0 && isdigit(contact[1]) > 0 && isdigit(contact[2]) > 0 && isdigit(contact[4]) > 0 && isdigit(contact[5]) > 0 && isdigit(contact[6]) > 0 && isdigit(contact[7]) > 0 && isdigit(contact[8]) > 0 && isdigit(contact[9]) > 0 && isdigit(contact[10]) > 0)
        return 1;

    else {
        printf("Error Phone!\n");
        return 0;
    }
}

Upvotes: 0

Views: 68

Answers (1)

l刘达
l刘达

Reputation: 74

The following code contains a function called validateContact(). It uses regex comparisons to achieve the check of the phone number the way you have asked. Hope this can help you.

#include <stdio.h>
#include <stdbool.h>
#include <regex.h>

bool validateContact(const char *contact) {
    regex_t preg;
    regcomp(&preg, "0[[:digit:]]{2}-[[:digit:]]{7}", REG_EXTENDED);
    if (regexec(&preg, contact, 0, NULL, 0) == 0) {
        return true;
    }
    return false;
}

int main() {
    printf("010-1234567 match: %d\n", validateContact("010-1234567"));
    printf("110-1234567 match: %d\n", validateContact("110-1234567"));
    printf("010_1234567 match: %d\n", validateContact("010_1234567"));
}

Upvotes: 3

Related Questions