I'm using ajax to make a server side form validation in laravel. All my validations are working fine except for one which i can figure out how to do it. Actually i have a field in my form for the ID number, which can take either 7 caracters for passport number, 9 caracters for ID card number or 20 caracters for temporary ID card number. How can i set a validation for size or lenght with 3 differents options?
function validation(e, f) {
var x = document.getElementsByClassName("alert-danger");
var y = "false";
var i;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/membre/modalValidation",
method: "post",
data: (e == 1) ? new FormData(document.getElementById("modal-danger4")) :
new FormData(document.getElementById("modal-danger8")),
processData: false,
dataType: 'json',
async: false,
contentType: false,
beforeSend: function() {
$(document).find('.alert-danger').text('');
},
success: function(data) {
if (data.status == 0) {
$.each(data.error, function(prefix, val) {
$('.m' + f + ' .' + prefix + '_error').text(val[0]);
});
} else {
}
for (i = 0; i < 30; i++) {
if (x[i].innerHTML) {
y = "true";
}
}
}
});
return y;
}
public function modalValidation(Request $request)
{
$newDate = Carbon::now()->subYears(10);
$validator = Validator::make($request->all(), [
'firstname' => ['required'],
'email' => ['required', 'unique:users', 'digits:9'],
'phone' => ['nullable', 'unique:users', 'email:rfc,dns'],
'email1' => ['required', 'unique:client__ents,email', 'digits:9'],
'phone1' => ['nullable', 'unique:client__ents,phone', 'email:rfc,dns'],
'name' => ['required'],
'job' => ['required'],
'CNI_number' => ['required', 'unique:users', 'digits_between:7,20'],
'CNI_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
'CNI_place' => ['required'],
'raison_sociale' => ['required'],
'forme_juridique' => ['required'],
'siteWeb' => ['nullable', 'url'],
'activité' => ['required'],
'num_contribuable' => ['required', 'unique:client__ents,Numero_contribuable', 'between:13,14'],
'NC_date' => ['required', 'date_format:d/m/Y', 'after:'.$newDate],
'siège' => ['required'],
'email2' => ['required', 'unique:responsable_ents,email', 'digits:9'],
'phone2' => ['nullable', 'unique:responsable_ents,phone', 'email:rfc,dns'],
'CNI_number1' => ['required', 'unique:responsable_ents,CNI_number', 'digits_between:7,20'],
'password' => ['required', 'min:8'],
'confirm_password' => ['same:password'],
'checkbox' => ['accepted'],
],
['confirm_password.same' => 'Ne correspond pas',
'accepted'=>'Veuillez cocher la case avant de continuer',
'required'=>'Ce champ est obligatoire',
'phone.unique'=>'Un utilisateur avec ce mail existe déjà',
'email.unique'=>'Un utilisateur avec ce numéro existe déjà',
'phone1.unique'=>'Un utilisateur avec ce mail existe déjà',
'email1.unique'=>'Un utilisateur avec ce numéro existe déjà',
'phone2.unique'=>'Un responsable avec ce mail existe déjà',
'email2.unique'=>'Un responsable avec ce numéro existe déjà',
'CNI_number.unique'=>'Un utilisateur avec ce numéro de CNI existe déjà',
'CNI_number1.unique'=>'Un responsable avec ce numéro de CNI existe déjà',
'num_contribuable.unique'=>'Un utilisateur avec ce numéro de contribuable existe déjà',
'digits'=>'Veuillez saisir un numéro valide à 9 chiffres',
'digits_between'=>'Numéro CNI(Passeport) non-conforme',
'email'=>'Ce mail est invalide. Doit inclure #',
'date_format'=>'Invalide. Veuillez saisir une date',
'CNI_date.after'=>'Votre CNI ou Passeport ou Récépissé est expiré',
'NC_date.after'=>'Votre Numéro de contribuable est expiré',
'url'=>'Invalide. Veuillez saisir un URL',
'password.min'=>'Minimum 8 caractères',
'num_contribuable.between'=>'Numéro de contribuable non-conforme',
]);
if ($validator->fails())
{
return response()->json(['status'=>0, 'error'=>$validator->errors()->toArray()]);
}
}
<div class="modal-body step-2 m2">
<center>
<h4>Pièce d'identité</h4>
</center>
<div class="form-group">
<label>Numéro CNI(ou Passeport)<i style="color:#FF0000">*</i> :</label>
<input type="number" name="CNI_number" class="form-control" placeholder="Entrer le numéro CNI">
<div class='alert-danger CNI_number_error'></div>
</div>
<div class="form-group">
<label>Date de délivrance<i style="color:#FF0000">*</i> :</label>
<input id="demo-one-input" name="CNI_date" class="form-control" placeholder="Entrer la date">
<div class='alert-danger CNI_date_error'></div>
</div>
<div class="form-group">
<label>Lieu de délivrance<i style="color:#FF0000">*</i> :</label>
<input type="text" name="CNI_place" class="form-control" placeholder="Entrer le lieu">
<div class='alert-danger CNI_place_error'></div>
</div>
<div class="form-group">
<label>Votre photo :</label>
<input type='file' accept="image/*" name="photo" class="form-control" placeholder="image portrait">
</div>
<div class="form-group">
<i style="color:#FF0000">*</i> Champs obligatoires
</div>
</div>
There is no standard validation rule to do this, but you can create a new custom rule.
Check out the documentantion for creating and applying custom rules here:
https://laravel.com/docs/8.x/validation#custom-validation-rules
This link might not scroll down to the right place right away, make sure to look for the topic called: "Custom Validation Rules"
I've been trying all answer founding in the net and that never work, i would like that the file who is save in the PDF folder and in the database behind a choose name while uploading.
This is my code :index.php
upload.php
INDEX.PHP:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="widht=device-widht, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Glisser-deposer </title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/dropzone.css">
</head>
<body>
<div id="main">
<div id="header">
<h1> Glisser-deposer les fichiers de telechargement<br> </h1>
</div>
<div id="content">
<form class="dropzone" id="file_upload"></form>
<button id="upload_btn">telechargement</button>
</div>
</div>
<script type="text/javascript" src="js/dropzone.js" ></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
Dropzone.autoDiscover = false;
$(document).ready(function () {
$(".dropzone").dropzone({
renameFilename: function (filename) {
return new Date().getTime() + '_' + filename;
}
});
});
var myDropzone = new Dropzone("#file_upload", {
url: "upload.php",
parallelUploads: 3,
uploadMultiple: true,
acceptedFiles: '.pdf',
clickable: true,
autoProcessQueue: false,
renameFilename: function (filename) {
name = new Date().getTime() + '-' + filename;
return name;
},
success: function(file,response){
if(response == 'true'){
$('#content .message').hide();
$('#content').append('<div classe="message success">Fichier Telecharger avec
succes.</div>');
}else{
$('#content').append('<div classe="message error">Le fichier ne peux etre
telecharger.</div>');
}
}
});
$('#upload_btn').click(function(){
myDropzone.processQueue();
});
</script>
</body>
</html>
UPLOAD.PHP :
<?php
/* Créer une connexion*/
$conn = mysqli_connect("localhost", "root", "","intranet"); // ("nom d'hôte", "nom
d'utilisateur", "mot de passe", " nom de la base")
/* Vérifier la connexion*/
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if($_FILES['file']['name'] != ''){
$file_names = '';
$total = count($_FILES['file']['name']);
for($i=0; $i<$total; $i++){
$filename = $_FILES['file']['name'][$i]; // Obtenez le nom du fichier
téléchargé.
$extension = pathinfo($filename,PATHINFO_EXTENSION); //Obtenez l'extension du
fichier téléchargé
$valid_extensions = array('pdf','.txt');
if(in_array($extension, $valid_extensions)){ // vérifier si le fichier de
téléchargement est un fichier pdf valide.
$new_name = rand() . ".". $extension;
$path = "PDF/" . $new_name;
move_uploaded_file($_FILES['file']['tmp_name'][$i], $path);
$file_names .= $new_name . " , ";
}else{
echo 'false';
}
}
// Enregistrer le nom des fichiers téléchargées dans la base de données
$sql = "INSERT INTO fichier VALUES('{$file_names}')";
if(mysqli_query($conn,$sql)){
echo 'true';
}else{
echo 'false';
}
}
?>
I am building a custom template in WordPress and I want to handle form submission using Ajax without page reloading and I always have the following error on my console 400 bad request. The form is not submitting to the server in other to handle the request. I have tried many possibilities but I didn't succeed.
Bellow is the form,is an image upload form
<form enctype="multipart/form-data" method="post" action="">
<div class="Success-div"></div>
<p> Vous devez nous fournir un certificat médical valide attestant vos aptitudes à
faire partir du club et faire part aux activités du club:</p>
<p class="statusMsg"></p>
<div class="form-group">
<label for="tel">Certificat médical</label><a style= "color:#DAA520;" href="#"
id="effectuerTest"> (je ne possède pas un certificat médical)</a>
<input type="file" name="certificatMedicalMajeur" class="form-control"
id="CertificatMedicalfichier" accept="application/pdf" required/>
</div>
<input type="submit" name="certificat-majeur-submit" id="submitbtn" class="certificat-
majeur-submit btn btn-primary pull-right" value="Enregistrer" />
</form>
Ajax code TO send the submitted data to the server
jQuery(document).on('click', '.certificat-majeur-submit', function (e) {
e.preventDefault();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var file_data = $('#CertificatMedicalfichier').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var $this = $(this);
jQuery.ajax({
type: 'POST',
data: {
data:form_data,
action: 'post_md_support_save'
},
url: ajaxurl,
processData : false,
success: function (response) {
jQuery('.Success-div').html(data.message);
},
error: function (response) {
console.log("error form");
}
});
});
And finally this is the code to handle the request file in function.php
add_action( 'wp_ajax_post_md_support_save', 'md_abonnements_save' );
add_action( 'wp_ajax_post_md_support_save', 'md_abonnements_save' );
function md_abonnements_save(){
echo "ajax responding";
die();
}
If you are using this code in Front End of your website, you should also add nopriv action hook: add_action( 'wp_ajax_nopriv_post_md_support_save', 'md_abonnements_save' );
I'm crazy with this error, I'm traying to make an Ajax login form, this is my code:
My HTML:
<div id='login-box' name='login-box' class='radius-all-tiny'>
<div class='bt-wrapper bt-wrapper-hover'>
<span class='bt-icon bt-icon-hover btn-users'></span>
</div>
<div id='login-banner' name='login-banner'>
" . $content['SESSION_BANNER'] . "
</div>
<div class='radius-all-tiny' id='login-error' name='login-error'>
</div>
<form id='login-frm' name='login-frm' method='post' action='./'>
<input type='text' id='usuario' name='usuario' placeholder='" . $content['SESSION_USER'] . "' />
<input type='password' id='contrasena' name='contrasena' placeholder='" . $content['SESSION_PASS'] . "' />
<div class='submit-wrap'><input class='bt-submit radius-all-medium' type='submit' id='enviar' name='enviar' value='" . $content['CONTACT_FRM_SEND'] . "' /></div>
</form>
</div>
My JS:
<script type='text/javascript'>
$(document).ready(function() {
// FORCE BROWSER NOT CACHE AJAX CALLS
$.ajaxSetup({ cache: false });
// HIDE ERROR DIALOG
$('#login-error').hide();
// LOGIN/OUT BUTTON BEHAVIOR
$('#bt-login').click(function(){
$('#login-error').hide();
$.fancybox.open({
href : '#login-box',
padding : 0,
onClosed : function() { }
});
});
// LOADING ANIMATION
var ajaxload = '<img src=\"../img/components/spinner-dark.gif\" alt=\"" . $content['MAIN_LOADING'] . "\" />';
$('#login-frm').bind('submit', function(){
// AUTHENTICATING...
// VALIDAMOS QUE NO HAYAN CAMPOS VACÍOS
if (($('#usuario').val().length < 1) || ($('#contrasena').val().length < 1))
{
$('#login-error').html('EMPTY');
$('#login-error').show();
return false;
}
// SI NO ESTÁN VACÍOS LOS CAMPOS, ENTONCES VALIDAMOS...
$.ajax({
type: 'POST',
cache: false,
url: '../libs/class.log.in.out.php',
data: {usuario: $('#usuario').val(), contrasena: $('#contrasena').val()},
dataType: 'json',
success: function(data)
{
if (data.success)
{
// ESCRIBIMOS LA VARIABLE DE SESIÓN
// CERRAMOS FANCYBOX
$.fancybox.close();
// RECARGAMOS LA PÁGINA PRINCIPAL
document.location.href = $('#urlactual');
}
else
{
// MOSTRAMOS ERROR DE AUTENTICACIÓN
$('#login-error').html('FAILED_AUTH');
$('#login-error').show();
}
}
});
return false;
});
});
</script>
My class.log.in.out.php:
/////////////////////////////////////////////////
// TRANSPORTADOR DE DATOS
/////////////////////////////////////////////////
$data = array(
'success' => false,
'msg' => 'No se encontró ningún dato...'
);
// SOLICITAMOS LOS VALORES DE CONEXIÓN
$usr = (isset($_REQUEST['usuario']) ? $_REQUEST['usuario'] : 'NULL');
$pwd = (isset($_REQUEST['contrasena']) ? $_REQUEST['contrasena'] : 'NULL');
// VALIDAMOS LOS DATOS
class_exists('Database') || require ('class.database.php');
$resp = "";
$thisstt = false;
// INSTANCIAMOS LA CLASE DE BASE DE DATOS
$dbs = new Database();
$datos = $dbs->logIn($usr, $pwd, "", $thisstt);
if ($thisstt)
$resp = $datos['usuario'];
else
$resp = "" . $datos['error'] . " Usuario: " . $usr . "";
// DEVOLVEMOS EL ESTADO DE LA VALIDACIÓN
$data = array(
'success' => $thisstt,
'msg' => utf8_encode($resp)
);
/////////////////////////////////////////////////
// EMPAQUETADO DE DATOS
/////////////////////////////////////////////////
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data);
I receive this response from de class.log.in.out.php (Using Firefox's developer tools):
When the authentication fail:
{"success":false,"msg":"Los datos ingresados son incorrectos... Usuario: 123"}
When the authentication is correct:
{"success":true,"msg":"gchinchilla"}
But Firefox says that the Syntax is incorrect, could you help me?
I apologize for my bad english, I'm learning it...
i do not see any need of converting array to object for json_encode.
i will suggest using :
echo json_encode($data);
instead of :
echo json_encode((object)$data);
SOLVED! There was an "codification error", I have converted the PHP file from UTF-8 to UTF-8 Without BOM.
More info here: http://es.wikipedia.org/wiki/UTF-8#Byte_order_mark_.28BOM.29
According to the official jQuery doc :
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
But in fact, it's not. With this code :
function saveCampagne (data){
$.ajax({
url : url,
type : "GET",
data : data,
statusCode:{
201 : function(campagne){
// JSON Decode
var Campagne = JSON.parse(campagne);
$("#zone-message").append('<div class="alert fade in" data-alert="alert"><a class="close" data-dismiss="alert" href="#">×</a><p><strong>C\'est Fait !</strong> La campagne a été ajoutée sous la référence #'+Campagne.id+'. Elle sera validée prochainement par un administrateur.</p></div>');
return Campagne;
},
200 : function(){
$("#zone-message").append('<div class="alert alert-error fade in" data-alert="alert"><a class="close" data-dismiss="alert" href="#">×</a><p><strong>Woops !</strong> Une erreur est survenue dans la création de la nouvelle campagne. Merci de ré-essayer ultérieurement.</p></div>');
}
},
success : function(campagne){
},
error : function(){
$("#zone-message").append('<div class="alert alert-error fade in" data-alert="alert"><a class="close" data-dismiss="alert" href="#">×</a><p><strong>Woops !</strong> Une erreur est survenue dans la création de la nouvelle société. Merci de ré-essayer ultérieurement.</p></div>');
}
});
}
i'm able to make the .append but the function never get data (passed through campagne, like success ) in my 201 : function(campagne){...}
Any Idea why it's not working like the doc say how it's works ?
Try removing the success and error handlers.