Add user input database verification

This commit is contained in:
2024-03-25 11:31:42 +01:00
parent d0a8306a20
commit 206e340012
3 changed files with 160 additions and 22 deletions

View File

@@ -12,19 +12,35 @@ use tui_textarea::{Input, Key, TextArea};
use anyhow::Result;
fn validate_user(textarea: &mut TextArea) -> bool {
if let Err(_) = textarea.lines()[0].parse::<u64>() {
textarea.set_style(Style::default().fg(Color::LightRed));
textarea.set_block(
Block::default()
.borders(Borders::ALL)
.title(format!("ERROR: Please enter a valid user number")),
);
false
} else {
textarea.set_style(Style::default().fg(Color::LightGreen));
textarea.set_block(Block::default().borders(Borders::ALL).title("OK"));
true
use crate::database::Database;
async fn validate_user(textarea: &mut TextArea<'_>, db: &Database) -> bool {
match textarea.lines()[0].parse::<u64>() {
Err(_) => {
textarea.set_style(Style::default().fg(Color::LightRed));
textarea.set_block(
Block::default()
.borders(Borders::ALL)
.title(format!("ERROR: Please enter a valid user number")),
);
false
}
Ok(value) => {
let db_user = db.user_exists(value as i64).await.is_ok();
if db_user {
textarea.set_style(Style::default().fg(Color::LightGreen));
textarea.set_block(Block::default().borders(Borders::ALL).title("OK"));
true
} else {
textarea.set_style(Style::default().fg(Color::LightRed));
textarea.set_block(
Block::default()
.borders(Borders::ALL)
.title(format!("ERROR: Please enter a valid user number")),
);
false
}
}
}
}
@@ -56,7 +72,7 @@ fn validate_rating(textarea: &mut TextArea) -> bool {
}
}
pub fn get_user_rating() -> Result<(String, String)> {
pub async fn get_user_rating(db: &Database) -> Result<(String, String)> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
@@ -70,7 +86,7 @@ pub fn get_user_rating() -> Result<(String, String)> {
textarea.set_placeholder_text("USER: Enter a valid user number (e.g. 156)");
let layout =
Layout::default().constraints([Constraint::Length(3), Constraint::Min(1)].as_slice());
let mut is_valid = validate_user(&mut textarea);
let mut is_valid = validate_user(&mut textarea, db).await;
loop {
term.draw(|f| {
@@ -95,7 +111,7 @@ pub fn get_user_rating() -> Result<(String, String)> {
input => {
// TextArea::input returns if the input modified its text
if textarea.input(input) {
is_valid = validate_user(&mut textarea);
is_valid = validate_user(&mut textarea, db).await;
}
}
}