Jump to content

Would this validation script work?


bigboss

Recommended Posts

I'm am looking to make a validation function. I have been thinking and would my general idea of having a system structured like this work?

 

<?php
#Register Page#
include 'functions.php';
if(isset($_POST)){
validate($_POST['username'],"username",1);
}

 

<?php
#Validate Function#
function validate($field_name,$field_type,$required){
if(isset($_POST)){
switch ($field_type)
case 'username':
#block of code
break;
}
}

 

I still haven't figured out how I would make sure that the required worked, at first I thought about a || in the first if in the validate function, or how to return errors to the register page or MD5 passwords and inset the values into the database. Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/149220-would-this-validation-script-work/
Share on other sites

NO

You are checking the post array here:

if(isset($_POST)){

and then checking again in the function:

if(isset($_POST)){

The $_POST array is outside the scope of the function so will always return nothing.

 

By using a switch / case you are assuming that the form fields names will always be username, etc. You could end up with a huge set of cases to cater for the forms in your website and you also have no way of checking if your form field names are in the switch / case.

 

You are better validating the fields simply using:

// check for an empty field
if(!strlen(trim($_POST['name']))) {
  $error = true;
}

 

or write a function i.e. check a username is between 5 and 10 characters

function checkUsername($name) {
$username = trim($name);
if(strlen($username) < 5 || strlen($username) > 10) {
   return false;
}
return true;
}

if(!checkUsername($_POST['username'])) {
  $errors = true;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.