How to force answers in a form?

Good day!!

I have a form including several type text, type radio and one type submit elements.

How can I make mandatory to fill all text fields and select one radio?
What I’d like to have is when press button, if all fields are not filled, then stay in the same page and add a sentence next to all unfilled fields, telling something like “Please fill this field”.

I have been trying with if(!isset($_POST[“variable”])), but nothing happened.
I’d appreciate any help and code examples.

Thanks a lot!!

Using just isset() is not enough because when the form is submitted all the form input elements will be set but may or may not have valid data in them.

So in your php script you need to check each sent form input value individually to check if it contains valid data. For example, if a form input is a username, you need to check in your php code if the sent username contains only valid characters for a username.

If any inputs are invalid you can then display an appropriate message next to the input field.

I’ve found one (probably rather noobie) way to do this.

For a text input, here’s one thing I do this in the HTML:

	<label for="name">Name</label>
	<input name="name" type="text" size="40" maxlength="60" id="name" value="<?php if (isset($_POST["name"])) {echo $name;} ?>">

And the check to make sure text has been entered and that it’s appropriate:

if (empty($name) || !preg_match("~^[a-z\\-'\\s]{1,60}$~i", $name)) { 
$error_msg[]="The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";

For radio buttons, here’s what I do:

In the form:

		<input type="radio" name="subject" id="sub1" value="Subject 1"  <?php if (isset($_POST["subject"])) {echo 'checked="checked"';} ?>>
		<label for="sub1">Subject 1</label>
		<input type="radio" name="subject" id="sub2" value="Subject 2" <?php if (isset($_POST["subject"])) {echo 'checked="checked"';} ?>>
		<label for="sub2">Subject 2</label>
		<input type="radio" name="subject" id="sub3" value="Subject 3" <?php if (isset($_POST["subject"])) {echo 'checked="checked"';} ?>>
		<label for="sub3">Subject 3</label>

And the check to make sure a selection has been made:

if (!isset($subject)) { 
$error_msg[]="Please choose a Subject";

Hope that helps.


I’ll be applying and posting results.

Thanks a lot!!