I want to get better on not nesting if-satments so much and got some help from my brother about how to think. So the thougt here is to create a function that validates that all fields in an form is filled in and with allowed caracters.
But I'm an expert on nested if:s and I need some help to learn a better way of doing it. My question is how I can do the same check in the function instead? What can I use that is good practise? Can I do it with an array?
My nested if statment is here (I'm supposed to do this to a much bigger form later on):
// If the submit button has been clicked
if(isset($_POST["login"])){
// Checks if username-field is empty and if allowed characters are used
if(empty($_POST['user']) or !preg_match("/^[a-zA-Z0-9 ]*$/", $_POST['user'])){
$error = "You can't leave a field empty and you can only use letters, numbers and space.";
}else{
// Checks if password-field is empty and if allowed characters are used
if(empty($_POST['pass']) or !preg_match("/^[a-zA-Z0-9 ]*$/", $_POST['pass'])){
$error = "You can't leave a field empty and you can only use letters, numbers and space.";
}else{
// Code here
}
}
}
And this is the base for what I want to try to do instead:
function validate(){
// Code here
}
// If the submit button has been clicked
if(isset($_POST["save"])){
if(validate(/*vaibles for each of the fields in the form*/)){
}else{
}
}