Skip to content

Commit 529edc1

Browse files
update
1 parent 658252d commit 529edc1

File tree

13 files changed

+140
-139
lines changed

13 files changed

+140
-139
lines changed

src/Methods/ValidatorMethod.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ public static function getMessage()
343343
// convert to array
344344
$message = !is_array($message) ? [$message] : $message;
345345

346-
return implode(' <br>', $message);
346+
return implode('<br>', $message);
347347
}
348348

349349
/**

src/Traits/PropertyTrait.php

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,6 @@ trait PropertyTrait {
2121
/** @var \Symfony\Component\HttpFoundation\JsonResponse|null */
2222
public $jsonResponse;
2323

24-
/** Flag to avoid double-sending responses */
25-
protected bool $responseSent = false;
26-
2724
/** @var bool Keep track of manually calling the validate method */
2825
private $isValidatedCalled = false;
2926

src/Traits/ValidateSuccessTrait.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Tamedevelopers\Validator\Traits;
66

7+
use Tamedevelopers\Support\Capsule\Manager;
78
use Tamedevelopers\Validator\Methods\Datatype;
89
use Tamedevelopers\Validator\Methods\CsrfToken;
910
use Tamedevelopers\Validator\Methods\RuleIndicator;
@@ -67,9 +68,13 @@ private function submitInitialization(?array $data = [])
6768

6869
if(!$this->param->has($this->csrf_token)){
6970
$this->message = ExceptionMessage::csrfTokenNotFound();
71+
72+
$this->json($this->message, 419);
7073
return $this;
7174
} elseif(!CsrfToken::validateToken($this->param->{$this->csrf_token})){
7275
$this->message = ExceptionMessage::csrfTokenMismatch();
76+
77+
$this->json($this->message, 419);
7378
return $this;
7479
}
7580
}

src/Traits/ValidatorTrait.php

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Closure;
88
use Tamedevelopers\Support\Tame;
99
use Tamedevelopers\Support\Server;
10+
use Tamedevelopers\Support\ApiResponse;
1011
use Tamedevelopers\Validator\Methods\Operator;
1112
use Tamedevelopers\Validator\Methods\GetRequestType;
1213
use Tamedevelopers\Validator\Methods\ValidatorMethod;
@@ -81,16 +82,27 @@ public function getForm($type = null)
8182
}
8283

8384
/**
84-
* Return a JSON response with status code and message
85+
* Return a JSON response
86+
* Common HTTP status codes for API responses:
87+
* - 200 OK - Request succeeded. Example: Successful login, data fetched successfully.
88+
* - 201 Created - Resource created successfully. Example: User registered, item stored.
89+
* - 400 Bad Request - Invalid request. Example: Malformed JSON, missing parameters.
90+
* - 401 Unauthorized - Authentication failed. Example: Wrong password, invalid token.
91+
* - 403 Forbidden - Not allowed. Example: User without permission attempts action.
92+
* - 404 Not Found - Resource missing. Example: User ID not found, endpoint invalid.
93+
* - 419 Page Expired - CSRF mismatch/session expired. Example: Invalid CSRF token.
94+
* - 422 Unprocessable Entity - Validation failed. Example: Invalid email, missing fields.
95+
* - 500 Internal Server Error - Server bug. Example: Database failure, fatal exception.
8596
*
86-
* @param int $response
87-
* @param mixed $message
88-
* @param int $statusCode
97+
* @param string $status
98+
* @param string $message
99+
* @param mixed $data
100+
* @param int $statusCode
89101
* @return \Symfony\Component\HttpFoundation\JsonResponse
90102
*/
91-
public static function json(int $response = 0, $message = null, int $statusCode = 200)
103+
public static function json($status, $message, $data = null, int $statusCode = 200)
92104
{
93-
return Tame::json($response, $message, $statusCode);
105+
return ApiResponse::json($status, $message, $data, $statusCode);
94106
}
95107

96108
/**

src/Validator.php

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -140,21 +140,13 @@ public function save($closure)
140140

141141
$response = $this->callback($closure);
142142

143-
dd(
144-
'sss'
145-
);
146-
exit();
147-
148143
// If user returns a JsonResponse in save, send and return it
149144
if (ValidatorMethod::isJsonResponse($response)) {
150-
if (!$this->responseSent) {
151-
$response->send();
152-
$this->responseSent = true;
153-
}
145+
// delete csrf session token
146+
// CsrfToken::unsetToken();
147+
148+
return $response->send();
154149
}
155-
156-
// delete csrf session token
157-
CsrfToken::unsetToken();
158150
}
159151

160152
return $this;

tests/include.php

Lines changed: 0 additions & 6 deletions
This file was deleted.

tests/include/form.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php
2+
3+
include_once __DIR__ . "/../../vendor/autoload.php";
4+
5+
$form = form()->post();
6+
Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
<?php
22

3-
include_once __DIR__ . "/include.php";
3+
include_once __DIR__ . "/form.php";
44

55

6-
$result = $form->token(true)->error(false)->rules([
6+
$result = $form->token(true)->error(true)->rules([
77
"string|name" => 'Please enter a name',
88
"str_len|name|<|5" => 'Name should be more than five(5) characters',
99
"email|email" => 'Please enter a valid email address',
@@ -16,19 +16,18 @@
1616
"enum:terms" => 'Accept terms and condition',
1717
])->validate(function($response){
1818

19-
return $response->json(1, $response->message);
19+
return $response->json('error', $response->getMessage(), [
20+
'class' => $response->getClass()
21+
]);
2022
})->save(function($response){
2123
// access the form data
2224
$param = $response->param;
2325

2426
// access parent scope data\ $data
25-
$attribute = $response->attribute;
26-
27-
// dump(
28-
// // $param->message,
29-
// $param->toArray(),
30-
// );
31-
32-
return $response->json(0, "Submitted Successfully");
27+
$attribute = $response->getAttribute();
28+
29+
return $response->json('success', "Submitted Successfully", [
30+
'class' => $response->getClass()
31+
]);
3332
});
3433

tests/style.css renamed to tests/include/style.css

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ input:focus{
5959
.mb-5{
6060
margin-bottom: 20px;
6161
}
62-
.errorMSg{
62+
.errorMsg{
6363
display: block;
6464
border-radius: 6px;
6565
padding: 5px 10px;

tests/index_ajax.php

Lines changed: 85 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,115 +1,111 @@
11
<?php
22

3-
include_once __DIR__ . "/include.php";
3+
include_once __DIR__ . "/include/form.php";
44
?>
55

66
<!DOCTYPE html>
77
<head>
88
<title>Form validation</title>
99
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
1010
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1">
11-
<link href="style.css" rel="stylesheet" type="text/css">
11+
<link href="include/style.css" rel="stylesheet" type="text/css">
1212
</head>
1313
<html>
1414
<body>
1515

16-
<form method="post" action="<?= tasset('tests/server.php', false, true);?>" class="form"
17-
onsubmit="return submitForm(this)">
18-
<h2>Form sample</h2>
19-
20-
<div class="errorMSg mb-5 <?= $form->getClass() ?>">
21-
<?= $form->getMessage() ?>
22-
</div>
16+
<form method="post" action="<?= tasset('tests/include/server.php', false, true);?>" class="form"
17+
onsubmit="return submitForm(this)">
18+
<h2>Form sample</h2>
19+
20+
<div class="errorMsg mb-5 <?= $form->getClass() ?>">
21+
<?= $form->getMessage() ?>
22+
</div>
2323

24-
<?php csrf() ?>
24+
<?php csrf() ?>
2525

26-
<div class="row">
27-
<div class="">
28-
<label for="html">Name</label>
29-
<input type="text" name="name" value="<?= $form->old('name'); ?>">
30-
</div>
31-
32-
<div class="">
33-
<label for="html">Email</label>
34-
<input type="text" name="email" value="<?= old('email'); ?>">
35-
</div>
36-
37-
<div class="">
38-
<label for="html">Age</label>
39-
<input type="number" name="age" value="<?= old('age'); ?>">
40-
</div>
41-
42-
<div class="">
43-
<label for="html">Loan Amount</label>
44-
<input type="number" step="any" name="amount" value="<?= old('amount'); ?>">
45-
</div>
46-
47-
<div class="">
48-
<label for="html">Message</label>
49-
<textarea name="message" rows="5" style="resize:none;"
50-
cols="81"><?= old('message'); ?></textarea>
51-
</div>
52-
53-
<div class="activities">
54-
<p class="title">
55-
Activities you're interested in:
56-
</p>
26+
<div class="row">
27+
<div class="">
28+
<label for="html">Name</label>
29+
<input type="text" name="name" value="<?= $form->old('name'); ?>">
30+
</div>
31+
32+
<div class="">
33+
<label for="html">Email</label>
34+
<input type="text" name="email" value="<?= old('email'); ?>">
35+
</div>
36+
37+
<div class="">
38+
<label for="html">Age</label>
39+
<input type="number" name="age" value="<?= old('age'); ?>">
40+
</div>
41+
42+
<div class="">
43+
<label for="html">Loan Amount</label>
44+
<input type="number" step="any" name="amount" value="<?= old('amount'); ?>">
45+
</div>
46+
47+
<div class="">
48+
<label for="html">Message</label>
49+
<textarea name="message" rows="5" style="resize:none;"
50+
cols="81"><?= old('message'); ?></textarea>
51+
</div>
5752

58-
<label for="reading">
59-
Reading
60-
<input type="checkbox" name="activities[]" value="reading" id="reading" <?= old('activities.reading') ? 'checked' : '' ?> >
61-
</label>
62-
<label for="writing">
63-
Writing
64-
<input type="checkbox" name="activities[]" value="writing" id="writing" <?= old('activities.writing') ? 'checked' : '' ?>>
65-
</label>
53+
<div class="activities">
54+
<p class="title">
55+
Activities you're interested in:
56+
</p>
6657

67-
<label for="terms" style="margin-top: 30px;">
68-
Accept terms
69-
<input type="checkbox" name="terms" id="terms"
70-
value="accepted" <?= old('terms') ? 'checked' : '' ?> >
71-
</label>
72-
</div>
58+
<label for="reading">
59+
Reading
60+
<input type="checkbox" name="activities[]" value="reading" id="reading" <?= old('activities.reading') ? 'checked' : '' ?> >
61+
</label>
62+
<label for="writing">
63+
Writing
64+
<input type="checkbox" name="activities[]" value="writing" id="writing" <?= old('activities.writing') ? 'checked' : '' ?>>
65+
</label>
7366

74-
<button type="submit" class="btn mt-2">Submit</button>
67+
<label for="terms" style="margin-top: 30px;">
68+
Accept terms
69+
<input type="checkbox" name="terms" id="terms"
70+
value="accepted" <?= old('terms') ? 'checked' : '' ?> >
71+
</label>
7572
</div>
76-
</form>
7773

74+
<button type="submit" class="btn mt-2">Submit</button>
75+
</div>
76+
</form>
7877

79-
<script>
80-
function submitForm(form){
81-
event.preventDefault();
78+
<script>
79+
function submitForm(form){
80+
event.preventDefault();
8281

83-
let formData = new FormData(form);
82+
let formData = new FormData(form);
8483

85-
// send via fetch
86-
fetch(form.action, {
87-
method: form.method, // POST
88-
body: formData
89-
})
90-
.then(response => response.text())
91-
.then(data => {
92-
// parse the JSON response
93-
// data = JSON.parse(data);
84+
// send via fetch
85+
fetch(form.action, {
86+
method: form.method, // POST
87+
body: formData
88+
})
89+
.then(response => response.text())
90+
.then(data => {
91+
// parse the JSON response
92+
data = JSON.parse(data);
9493

95-
console.log(
96-
data,
97-
// data.response,
98-
// data.message
99-
);
100-
return false;
101-
// handle success/error response from server
102-
if(data.status === "success"){
103-
alert("Form submitted successfully ✅");
104-
105-
} else {
106-
alert("Error: " + data.message);
107-
}
108-
})
109-
.catch(error => {
110-
console.error("Error:", error);
111-
});
112-
}
113-
</script>
94+
let msg = data.message;
95+
let div = document.querySelector('.errorMsg');
96+
97+
div.innerHTML = data.message;
98+
div.className = "errorMsg " + data.data.class;
99+
100+
// handle success/error response from server
101+
if(data.status === "success"){
102+
103+
}
104+
})
105+
.catch(error => {
106+
console.error("Error:", error);
107+
});
108+
}
109+
</script>
114110
</body>
115111
</html>

0 commit comments

Comments
 (0)