使用 Ncurses (FORM) 进行表单验证

问题描述 投票:0回答:1

无法实现字符输入验证。我已经勾勒出一个用于输入验证的简单程序的代码。字段中显示各种字符。

#include <form.h>

int main() {
    initscr();
    curs_set(1);
    WINDOW *win = newwin(5, 40, 10, 10);
    keypad(win, TRUE);
    box(win, 0, 0);
    wrefresh(win);

    FIELD *fields[2];
    fields[0] = new_field(1, 20, 2, 2, 0, 0);
    fields[1] = NULL;
    set_field_type(fields[0], TYPE_REGEXP, "^[0-9]*$");
    set_field_opts(fields[0], O_VISIBLE | O_ACTIVE | O_EDIT);

    FORM *form = new_form(fields);
    set_form_win(form, win);
    set_form_sub(form, derwin(win, 3, 38, 1, 1));
    post_form(form);
    wrefresh(win);

    int ch;
    while ((ch = wgetch(win)) != KEY_F(1)) {
        int status = form_driver(form, ch);
        if (status == E_INVALID_FIELD) {
            form_driver(form, REQ_VALIDATION);
        } else if (status == E_OK) {
            wrefresh(win);
        }
    }

    unpost_form(form);
    free_form(form);
    free_field(fields[0]);
    endwin();

    return 0;
}

enter image description here

c forms field ncurses
1个回答
0
投票

两个问题:

  • form_driver(form, ch)
    不会验证字段,只有
    form_driver(form, REQ_VALIDATION);
  • 使用您使用的正则表达式,
    field[0}
    必须完全填充数字,因此只要您没有输入 20 位数字,验证就会导致错误。来自 man set_field_opts

请注意,正则表达式必须匹配整个字段。例如,如果您有一个八个字符宽的字段,则正则表达式“^[0-9]$”始终意味着您必须用数字填充所有八个位置。如果您想允许更少的数字,您可以使用例如“^[0-9] *$”,这适用于尾随空格(最多为空字段),或“^ [0-9] *$” " 这对于数字周围的前导和尾随空格很有用。

关于这些点,我已经修改了您的代码:

#include <form.h>

int main() {
    initscr();
    curs_set(1);
    WINDOW *win = newwin(5, 40, 10, 10);
    keypad(win, TRUE);
    box(win, 0, 0);
    wrefresh(win);

    FIELD *fields[2];
    fields[0] = new_field(1, 20, 2, 2, 0, 0);
    fields[1] = NULL;
    set_field_type(fields[0], TYPE_REGEXP, "^[0-9]* *$");
    set_field_opts(fields[0], O_VISIBLE | O_ACTIVE | O_EDIT);

    FORM *form = new_form(fields);
    set_form_win(form, win);
    set_form_sub(form, derwin(win, 3, 38, 1, 1));
    post_form(form);
    wrefresh(win);

    int ch;
    while ((ch = wgetch(win)) != KEY_F(1)) {
        int status = form_driver(form, ch);
        if( status == E_OK ) {
            status = form_driver(form, REQ_VALIDATION);
        }
        if (status == E_INVALID_FIELD) {
       // handle invalid input
       fprintf( stderr, "invalid input: %c\n", ch );
        } else if (status == E_OK) {
            wrefresh(win);
        }
    }

    unpost_form(form);
    free_form(form);
    free_field(fields[0]);
    endwin();

    return 0;
}

当你运行它并输入 31K 时,你将进入 stderr

无效输入:K

© www.soinside.com 2019 - 2024. All rights reserved.