i want to validate this form with php. I want to use regex, and the strlen() function. this is the Form ===>
<form class="form" action="index.php" method="post" name="form">
<p class="form_field">
<label>Name :</label>
<input class="input" type="text" name="name" placeholder="Name">
* <?php echo $nameErr; ?><br>
</p>
<p class="form_field">
<label>Email :</label>
<input class="input" type="text" name="email" placeholder="Email">
* <?php echo $emailErr; ?><br>
</p>
<p class="form_field">
<label>Gender :</label>
<input class="radio" type="radio" name="gender"> male
<input class="radio" type="radio" name="gender"> female
* <?php echo $genderErr; ?><br>
</p>
<p class="form_field">
<label>Website :</label>
<input type="text" name="website" placeholder="Website">
<?php echo $websiteErr; ?> <br>
</p>
<p class="form_field">
<label>Comment :</label>
<textarea rows="5" cols="30" name="comment" placeholder="your comment ..."></textarea>
* <?php echo $commentErr; ?> <br>
</p>
<input class="submit" type="submit" name="submit" placeholder="Submit" >
and this is my php function to validate it ==>
function validate_forms($user_input, string $field){
$input_length = strlen($user_input);
if($field = "name"){
if($input_length > 8){
$message = "the name should be less than 32 characters";
} else{
if( !preg_match("/^[A-Za-z. ]*$/", $user_input) ){
$message = "Only letters and white space are allowed ";
} else {
$get_input = $user_input;
}
}
} elseif ($field = "URL") {
if(!preg_match("/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:[a-zA-Z])|\d+\.\d+\.\d+\.\d+)/", $_POST['website'])){
$message = "Please enter a valid url ";
} else {
$get_input = $user_input;
}
} elseif ($field = "email") {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$get_input = $user_input;
}
}
return $message;}
What i want to accomplish is to make my function return the $message variable if no condition is met, and get and return the $user_input if all conditions are met.
i think it is possible to return an array but i don't know how.
Also i think i'm not respecting the best practices here so it will be so nice of you to help understand the best way to validate my form(a more faster and secure way)
this is for learning purposes , so any more informations or books, tutorials and courses recommendations are welcomed.Thank you in advance
PS: I know an Object Oriented approach will be better in this case, but i want to learn the procedural way first.