Form validation

后端 未结 4 1805
灰色年华
灰色年华 2021-01-16 23:46

I need to create a form that has many of the same fields, that have to be inserted into a database, but the problem I have is that if a user only fills in one or two of the

4条回答
  •  被撕碎了的回忆
    2021-01-17 00:04

    I don't know the exact PHP syntax, but I'll write some pseudo-code that ought to do the trick. The basic idea is when you retrieve the $_POST values, you'll want to create a new hash that has values that are acceptable and then you can pass that hash to whatever methods needs to build out queries or whatever. The way I'll do this is to remove invalid values from the hash entirely, so it appears they were never there. Obviously, you can do this differently (mark them as invalid, etc).

    $cleaned_args = array();
    
    foreach ($_POST as $key => $value) {
        if ($_POST[$key] != "" && is_valid_email($_POST[$key])) {
            $cleaned_args[$key] = $_POST[$key];
        }
    
    make_db_call_or_whatever($cleaned_args);
    

    where is_valid_email is a method that maybe PHP has or you have to write. You could even generalize the if clause into an is_valid($_POST[arg]) method if you want, but it depends on how complex the situation is.

    Hopefully, this helps to give you an idea of how to do this. I think this will be easier than dynamically removing inputs with JavaScript before the form submission and, as mentioned, will be more secure than doing it only on the client side.

提交回复
热议问题