Please could someone tell me the best way to wrtite this in PHP i am validating gender in a text box i do not want to use radio button. at present my code is like this but not working

if(preg_match("/gender/i",$field))
        {
          if(!preg_match("/^M,F $/",$value))
          {
            $errors[] = "$value is not a valid gender.";
          }
        }

Could some tell me how to make sure value is either M OR F user inputed in box

Why a text box? That forces you to validate essentially unchecked input. If you don't want to use radio buttons, how about a dropdown menu with M or F?

In addition to deceptikon. Supposing you have a form field named gender which sends the data with POST method:

<input type="text" name="gender" />

This can work:

if(!in_array(strtolower(trim($_POST['gender'])),array('m','male','f','female'))
{
    $errors[] = ''; # message
}

if nothing is matching the array values then it sends an error. This can work also with select or radio buttons which, in my opinion, are better solutions.

Member Avatar for LastMitch

@onofej

Do you have DB?

If so, you can used what cereal wrote to check the valve either M or F

<input type="text" name="gender" />
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.