Again, I am working with this form validation. Everything works fine and I like the way it works. Unless I want to add ajax function to check weather username already exist from database. Any body can help? I am not really familiar with ajax and Jquery.
This the php consist of html form, index.php :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo " Form submited....!!!! <br/>";
echo '<br/> Username = '.$_POST['username'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body >
<form method="POST" action="">
<div class="form-group">
<label for="txtUserName" class="col-lg-3 control-label">Username :</label>
<div class="col-lg-9">
<input type="text" id="txtUserName" name="username" placeholder="Create Username" >
<p><small id="elmUserNameError" class="errorMsg"></small></p>
</div>
</div>
<button type="button" onClick="return check_form(this.form);">Submit</button>
</form>
<script>
function check_form(form) {
if(validateForm(form) === true ) {
form.submit();
return true;
}
}
function validateForm(theForm) {
with(theForm) {
return (
isNotEmpty(txtUserName, "Please Create username!", elmUserNameError)
&& isUsernameMinMax(txtUserName, 6,10, "Username must between 6 - 10 characters", elmUserNameError)
&& isUpperCase(txtUserName, "Create Username with UPPERCASE!", elmUserNameError)
&& isMatching(txtUserName, "Username must be UPPERCASE with number and underscore. No white space allowed", elmUserNameError)
// problem here......
&& isUserExis(txtUserName, "Username already exist!", elmUserNameError)
);
return false;
}
return true;
}
function isNotEmpty(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim() !== "");
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isUsernameMinMax(inputElm, minLength, maxLength, errMsg, errElm) {
var inputValue = inputElm.value.trim();
var isValid = (inputValue.length >= minLength) && (inputValue.length <= maxLength);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isUpperCase(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[^a-z]*$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function isMatching(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\w+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
function postValidate(isValid, errMsg, errElm, inputElm) {
if (!isValid) {
// Show errMsg on errElm, if provided.
if (errElm !== undefined && errElm !== null
&& errMsg !== undefined && errMsg !== null) {
errElm.innerHTML = errMsg;
}
// Set focus on Input Element for correcting error, if provided.
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.add("errorBox"); // Add class for styling
inputElm.focus();
}
} else {
// Clear previous error message on errElm, if provided.
if (errElm !== undefined && errElm !== null) {
errElm.innerHTML = "";
}
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.remove("errorBox");
}
}
}
</script>
</body>
</html>
I need to add this function but I have no idea how to return ajax call to validate the result. For example here, as I manually write, when user enter 'DADADA', it will return error 'Username already exist!'.
function isUserExis(inputElm, errMsg, errElm){
// maybe ajax call here....
var isValid = (inputElm.value.trim() !== "DADADA");
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}
This my php file to be called, check_username.php :
<?php
include('config.php'); // class and configuration
$users = new Users($db);
if($_REQUEST)
{
$username = $_REQUEST['username'];
if ($users->UsernameExist($username) === true) {
echo 'That Username already exist!';
}
}
?>
Related
I apologize for this being a bit lengthy but I wanted to show the code and not leave anything out.
The Goal: The user submits a registration form that submits the form to a database which adds the info plus a unique string to the database. Once the user submits an email is sent to the user that contains a link to a php page that has that unique string as a URL identifier at the end like so:
xyz.com/activate.php?uid=292ca78b727593baad9a
When the user clicks that link they are taken that page where they will fill out another form and when they click submit it will activate their account.
The Problem: When the user goes to the link provided they receive an error from my validation page like so:
Undefined index: variable in process.php
BUT when the user deletes the URL identifier so the URL shows as:
xyz.com/activate.php
The user does not receive an error and the validation page (process.php) works properly. I have attempted to use the identifier with a $_GET['uid'] and checking if it exists before running the code but the result was the same. I cannot find an answer when attempting to google this issue so I apologize if this has been asked before.
The Question: Why does this work without the URL identifier but not with it? I do realize the URL identifier basically does a $_REQUEST when the page first loads which is what runs the process.php. Is there a way to prevent that?
So that you guys know the code I am working with I have posted it below.
activate.php:
<?php
// validate the form.
require_once('process.php');
$validation_rules = array(
'company_name' => array(
'required' => true,
'min-length' => 2
)
);
$db_error = '';
$validate = new validator();
$validate->validate($validation_rules);
if ($validate->validate_result()) {
// the validation passed!
}
?>
<div class="bg v-100 cm-hero-activate">
<div class="v-100">
<div class="v-set v-mid">
<form class="v-mid v-bg-white <?php if(!$validate->validate_result() && $_POST || !empty($error)) { echo "shake"; } ?>" name="activation" action="" method="post">
<fieldset>
<div class="form-content">
<div id="content">
<div class="form-inner in" data-id="1" data-name="activate">
<h1>ACTIVATE YOUR ACCOUNT</h1>
<div class="form-section">
<h2>Personal Info</h2>
<?php if (!empty($db_error)) {
echo $db_error;
} ?>
<div class="field-group">
<input type="text" id="company_name" class="field required" name="company_name" value="<?php $validate->form_value('company_name'); ?>">
<label for="company_name" class="placeholder">Company Name</label>
<?php $validate->error(array('field' => 'company_name', 'display_error' => 'single')); ?>
</div>
</div>
<div class="field-bottom">
<button name="submit" data-name="activate" class="bttn btn-dark btn-hover-gloss">ACTIVATE MY ACCOUNT</button>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
process.php:
<?php
class validator {
private $validation_rules;
private $errors = array();
private $validate_result = array();
public function validate($rules) {
$this->validation_rules = $rules;
if($this->validation_rules && $_REQUEST) {
foreach($this->validation_rules as $field => $rules) {
$result = $this->process_validation($field, $rules);
if($result == false) {
$this->validate_result[] = 0;
} elseif($result == true) {
$this->validate_result[] = 1;
}
}
}
}
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
public function validate_result() {
if($this->validation_rules) {
if($_REQUEST) {
$final_result = true;
$length = count($this->validate_result);
for($i=0;$i < $length; $i++) {
if($this->validate_result[$i] == 0) {
$final_result = false;
}
}
return $final_result;
}
}
}
private function process_validation($field, $rules) {
$result = true;
$error = array();
foreach($rules as $rule => $value) {
if($rule == 'required' && $value == true) {
if(!$this->required($field, $value)) {
$error[] = "$field - required";
$result = false;
}
} elseif($rule == 'min-length') {
if(!$this->minlength($field, $value)) {
$error[] = "$field - minimun length is $value";
$result = false;
}
}
}
$this->errors[] = array($field => $error);
return $result;
}
public function error($data = '') {
if($this->validation_rules) {
if($_REQUEST) {
foreach($this->errors as $err) {
if(isset($data['field'])) {
foreach($err as $field => $field_error) {
if($data['field'] == $field) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next:
}
}
} else {
foreach($err as $field => $field_error) {
foreach($field_error as $error_data) {
if(isset($data['display_error']) == 'single') {
echo '<p class="error">' . $error_data . '</p>';
goto next1;
} else {
echo '<p class="error">' . $error_data . '</p>';
}
}
next1:
}
}
}
}
}
}
private function required($field, $value) {
if(empty($_REQUEST[$field])) {
return false;
} else {
return true;
}
}
private function minlength($field, $value) {
if(strlen($_REQUEST[$field]) < $value) {
return false;
} else {
return true;
}
}
?>
EDIT: it seems that the error is happening on the if statement in the min-length function: if(strlen($_REQUEST[$field]) < $value)
EDIT 2: This may also be of some use. The textbox is being filled with this: <br /><font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'><tr><th align='left' bgcolor='#f57900' colspan=
and underneath that I receive this error: Notice: Undefined index: company_name in C:\...\process.php on line 25 Call Stack #TimeMemoryFunctionLocation 10.0005369632{main}( )...\activate.php:0 20.0029403928validator->form_value( )...\activate.php:80 ">
Your $field_name doesn't exist in the $_REQUEST array which is why you are getting your undefined index error.
You are not checking if the value is set - just accessing it via $_REQUEST[$field_name] in your if statement.
Change
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && $_REQUEST[$field_name]) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
To
public function form_value($field_name = '') {
if($this->validation_rules) {
if($_REQUEST && isset($_REQUEST[$field_name])) {
if(!$this->validate_result()) {
echo $_REQUEST[$field_name];
}
}
}
}
Unrelated Tips.
Aim for cleaner - and more concise readable code.
$input = [
'name' => 'Matthew',
];
$rules = [
'name' => 'required|string',
];
$v = (new Validator())->validate($input, $rules);
if ($v->fails()) {
// Do something with $v->errors();
return;
}
// Do something with validated input
Try and avoid using else or elseif wherever possible. This can be achieved by looking for the negative first, and exiting early. Try not to have too many levels of nesting. It makes your code extremely difficult to read and increases cyclomatic complexity.
Also - take a look at an MVC framework which should help you to structure your code. A good start would be something like Laravel https://laravel.com/ there are good tutorials on https://laracasts.com/
You are getting this error because you have logic like
if($this->validation_rules && $_REQUEST) {
In PHP, an empty array is falsy and a non-empty one, truthy.
$_REQUEST is a combination of $_GET, $_POST and $_COOKIE.
When you add the uid query parameter, $_REQUEST will not be empty and therefore not falsy and your validator will attempt to run but without the expected POST data (such as company_name).
If you're only wanting to validate POST data, you should only be inspecting $_POST.
See Gravy's answer for safer ways to check for the existence of array keys.
<?php
class Validator {
public $errors = array(
'password' => '',
'email' => '');
const PASSWORD_MINCHARS = 8;
public function checkEmail($email) {
if ($this->checkEmpty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Please provide a valid email";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['email'] = "Please provide a value for the email";
return FALSE;
}
}
public function checkPassword($string) {
if ($this->checkEmpty($string)) {
if (strlen($string) < self::PASSWORD_MINCHARS) {
$this->errors['password'] = "The password should be atleast ".self::PASSWORD_MINCHARS." characters long.";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['password'] = "Please provide a value for the password";
return FALSE;
}
}
private function checkEmpty($string) {
if (!empty($string)) {
return TRUE;
}
return FALSE;
}
public function displayErrors() {
$output = '';
foreach ($this->errors as $error) {
if (!empty($error)) {
$output .= '<p>'.$error.'</p>';
}
}
return $output;
}
}
?>
<?php
require 'Validator.php';
$validator = new Validator();
$email = '';
$password = '';
if ($validator->checkPassword($password) && $validator->checkEmail($email)) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
?>
The above code comes from two separate files. The one that comes begins with class Validator comes from Validator.php while the one that begins with the require function comes from index.php. So am just wondering why the method call that is $validator->displayErrors() in index.php only displays one error at a time instead of displaying them all at once.
There is only one error displayed because of your condition:
if ($validator->checkPassword($password) && $validator->checkEmail($email))
It executes your checkPassword method first, it returns false and so the second condition (which should execute the second validation method) is never checked.
You can avoid this by executing the validation methods first:
$validPassword = $validator->checkPassword($password);
$validEmail = $validator->checkEmail($email);
if ($validPassword && $validEmail) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
Replace
if ($validator->checkPassword($password) && $validator->checkEmail($email))
with
if ($validator->checkPassword($password) || $validator->checkEmail($email)) {
I have a user defined function, it takes one argument as an array for the form required fields. It checks if these fields are empty or not. If they are empty it will return a message and stop processing the form.
<?php
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
}
}
return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
echo check_required_fields($required_array);
}
?>
<html>
<body>
<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
The function is returning this error even when the form required fields are filled? how to fix this?
How can i use just use the function with out writing the word echo before its name?
I want to use this function so i don't have to manually write the if and else statement for every field in the form.
I think you want to do like this?
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) {
return "You have errors"; //This indicates that there are errors
}
}
}
or why not just:
function check_required_fields($required_array) {
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname])) {
return "You have errors"; //This indicates that there are errors
}
}
}
UPDATE:
Change:
$required_array = array('name', 'age'); //This just sets strings name and age into the array
to:
$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form
I'm collecting form data, sending that to PHP validation script through AJAX call. The issue is on special characters the php validation script is not working as expected.
HTML:
<input type="text" name="firstName" class="firstName"
placeholder="[first name]" required autofocus maxlength="25" size="25" />
JS:
$(".button").click(function () {
var firstName = encodeURIComponent($("input.firstName").val());
var datastring = "firstName=" + firstName;
$.ajax({
type: "POST",
url: "/scripts/validateSignup.php",
data: datastring,
cache: false,
success: function (errorMessage) {
//print to screen
}
});
});
PHP Validation
$postData = $_POST;
if (Filter::validateString($postData['firstName']) == false) {
echo "Oops! Some characters used in your first name are not valid.";
}
PHP Filter
//Returns true if string is good, false otherwise
public static function validateString($string) {
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.\,\-\_\'\"\#\?\!\:\;\$\#\%\&\+\= a-zA-Z0-9()]/", $string) == true) {
return false;
} else {
return true;
}
}
}
On an empty string it prints error to screen just fine. But if I do something like "~!##$%^&*()", then it accepts the string as good and doesnt throw and error, even though the result of preg_match == false.
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/", $string) == true) {
return false;
} else {
return true;
}
}
That is more valid regex, but not the result you want: you're checking for pretty much all input, so it'll match "abcd" and return false as well. There are 11 characters with special meanings to regular expressions, only those and the " need to be escaped: ^$[]()|.*+-
Try this:-
<?php
$string = "tes$%tname"; // invalid string
//$string = "testname"; // valid string
if(test($string) == false)
{
echo "String is invalid";
}
function test($string){
$string = trim($string);
if ($string == null || $string == "") {
return false;
} else {
if (preg_match("/[^\.,\-_'\"#?!:;\$#&\+=\sa-zA-Z0-9\(\)]/",$string) == true) {
return false;
} else {
return true;
}
}
}
?>
PHPFiddle is here:- http://phpfiddle.org/main/code/cdu-xg2
I am writing a form validation code in PHP. Below is the code.
the element with id #questionSubmit is a form with 6 text fields (code, question, answer, option1, option2, option3, option4, option5) and a submit button.
<form id="createQuestionForm" action="" method="POST">
Question Code: <input id="code" class="createQuestionTextBox1" type="text" name="questionCode">
Question Name: <input id="question" class="createQuestionTextBox1" type="text" name="questionName">
Correct Answer: <input id="answer" class="createQuestionTextBox1" type="text" name="correctAnswer">
Option 1: <input id="option1" class="createQuestionTextBox2" type="text" name="option_1">
Option 2: <input id="option2" class="createQuestionTextBox2" type="text" name="option_2">
Option 3 <input id="option3" class="createQuestionTextBox2" type="text" name="option_3">
Option 4 <input id="option4" class="createQuestionTextBox2" type="text" name="option_4">
Option 5 <input id="option5" class="createQuestionTextBox2" type="text" name="option_5">
<input type="Submit" id="questionSubmit" value="Create Question"></input>
</form>
function SubmitFormCreationData() {
$("#questionSubmit").click(function() {
if (CheckCodeField($("#code").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#question").val()) == false) {
return false;
} else if (CheckCorrectAnswerField($("#answer").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option1").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option2").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option3").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option4").val()) == false) {
return false;
} else if (CheckAnswerNameFields($("#option5").val()) == false) {
return false;
} else {
$.post("InsertNewQuestion.php", $('#createQuestionForm').serialize());
alert('Quiz Created');
window.setTimeout(delay,2000);
return true;
}
return false;
});
}
function CheckAnswerNameFields(value) {
var isValid = true;
if (value == "")
isValid = false;
if (value == null)
isValid = false;
for(LCV = 0;LCV <= (count(value)-1); LCV++) {
if(value[LCV] == "'")
isValid = false;
if(value[LCV] == '"')
isValid = false;
}
return isValid;
}
function CheckCodeField(value) {
var isValid = true;
if(isInteger(value) == false)
isValid = false;
if(value < 100000)
isValid = false;
if(value > 999999)
isValid = false;
return isValid;
}
function CheckCorrectAnswerField(value) {
var isValid = true;
if(isInteger(value) == false)
isValid = false;
if(value < 1)
isValid = false;
if(value > 5)
isValid = false;
return isValid;
}
function isInteger(possibleInteger) {
return /^[\d]+$/.text(possibleInteger);
}
Now if the first field is entered correctly then the output is as wanted, false is returned. However if the first field is entered correctly and the rest are blank then the page refreshes, however it should be returning false because I check if the question and option fields are blank. Why is this happening?
$("#questionSubmit").click(function() {
$.post("InsertNewQuestion.php", $('#createQuestionForm').serialize(), function(data){
if(data=='SUCCESS'){
alert('Quiz Created');
window.setTimeout(delay,2000);
return true;
}
else{
var alertx='';
for(i=0;i<data.split('-').length-1;i++) alertx += data.split('-')[i].toString()+"\n";
alert(alertx);
}
});
return false;
});
insertnewquestion.php
extract($_POST);
$errors = '';
if(!in_array($questionCode,range(100000,999999))) $errors .= 'Invalid code-';
if(!in_array($correctAnswer,range(1,5))) $errors .= "Invalid answer-";
for($i=1;$i<=6;$i++){
$var = $i==6 ? $questionName : ${'option_'.$i};
if(empty($var) || strstr($var,'"') || strstr($var,"'")) $errors.= "Invalid ".($i==6?"question name":"option $i")."-";
}
echo $errors=='' ? 'SUCCESS':$errors;
Try and write if work correctly