How access element attribute inside Parsley Validation - validation

I need get attributes of element inside Parsley validation, I can using jQuery and selector, but I think it not the best way, have another way to do it?
See below my validation and html code:
(function () {
'use strict';
// Validate xml extension.
window.ParsleyValidator.addValidator('filetype',
function (value, requirement) {
var ext = value.split('.').pop().toLowerCase();
return ext === requirement;
}, 32)
.addMessage('en', 'filetype', 'The selected file must be an %s file.');
}());
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://cdn.bootcss.com/parsley.js/2.0.7/parsley.js"></script>
<div class="container">
<form class="form-horizontal" role="form" data-parsley-validate>
<div class="form-group">
<label for="file" class="col-sm-2 control-label">File</label>
<div class="col-sm-4">
<input type="file"
name="file[]"
id="file"
class="form-control"
multiple="multiple"
data-buttonText="Escolha arquivo"
data-iconName="fa fa-folder-open"
data-parsley-filetype="xml"
required>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<button type="submit" class="btn btn-default">Salvar</button>
</div>
</div>
</form>
</div>

The current version doesn't really give you access; everything you need should be in requirement. It could be an array with multiple values, though.
A future should allow you to access any attribute starting with data-parsley-filetype-, but there's no way to know from your example what you are actually trying to achieve, so I don't know if that would help.

you need to access the argument directly:
window.Parsley
.addValidator('customvalidator', {
validateNumber: function (value, requirement) {
var element = arguments[2].$element.parent();
//logic here...
},
requirementType: 'integer'
});

Related

Partial View rendered in modal via ajax missing javascript events

Im having issues when placing html content from partial view into modal content via ajax, not all events defined in _layout.cshtml are being attached to elements in modal content.
Setup:
_Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
//custom css is here.
</head>
<body>
#RenderBody()
<partial name="_Modals" /> <-- all variations of modals exist in this file
//custom javascript files <-- **this is failing to attached to modal content**
#RenderSection("CustomScriptsSection", false);
</body>
</html>
_CustomLayout.cshtml
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<partial name="_SideBar" />
<main>
<partial name="_NavBar" />
<div>
#RenderBody()
<partial name="_Footer" />
</div>
</main>
#section CustomScriptsSection{
#RenderSection("Scripts", false)
}
_Viewstart.cshtml
#{
Layout = "~/Views/Shared/_CustomLayout.cshtml";
}
The Ajax Call snippet from a standard razor view(not a page).
#section Scripts{
$('#DefaultModelBtn').on('click', function (e) {
var RegisterURLPartial = "/Home/RegisterPartial"
$('#modal-default').modal('show');
$('#modal-default').off('shown.bs.modal').on('shown.bs.modal', function () {
if ($('#PartialContainer').length) {
$('#PartialContainer').load(RegisterURLPartial, function (response, status, xhr) {
});
}
});
});
}
Controller Method for the Partial Page
public virtual IActionResult RegisterPartial() => PartialView("~/Views/Home/Partial/_Register.cshtml");
The partial Page itself (ambiguous Action, Id, and Controller names)
<form id="someId" asp-action="someAction" asp-controller="someController" method="post">
<div class="input-group input-group-outline mb-3">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" type="text" class="form-control" autocomplete="off">
</div>
<div class="input-group input-group-outline mb-3">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" type="email" class="form-control" autocomplete="off">
</div>
<div class="input-group input-group-outline mb-3">
<label asp-for="Password" class="form-label"></label>
<input asp-for="Password" type="password" class="form-control" autocomplete="off">
</div>
<div class="text-center">
<button type="submit" class="btn btn-lg bg-gradient-primary btn-lg w-100 mt-4 mb-0">Sign Up</button>
</div>
</form>
What I noticed was the css is being formatted properly, but the javascript that attaches to those css class are not working, eg. focus event is missing in the modal. (input-group-outline css class is missing focus event)
No Razor Pages are used at all (#page not used).
Thanks for the help guys.

Laravel Vuejs form builder

In my project i have some events, each with a number of tags.
These tags are defined by the administrator user.
Some of these tags may have parameters.
For example, an email tag has two "Sender" and "Receiver" parameters.
Or the transfer tag has 2 parameters "From" and "To". and etc.
Do I have to use the form builder?
How do I implement this using Laravel and Vuejs?
Use Vue JS Component in Laravel like this.
Create Contact.vue component inside resources\assets\js\components then place your Vuejs there.
<template>
<div>
<h1>Contacts</h1>
<form action="#" #submit.prevent="createContact()">
<div class="form-group">
<label>Name</label>
<input v-model="contact.name" type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input v-model="contact.email" type="text" name="email" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">New Contact</button>
</div>
</form>
</div>
</template>
<script>
export default {
data: function(){
return {
contact:{
name:'',
email:'',
}
}
},
methods: {
createContact: function(){
//call axios to submit the form values in your Laravel controller method
let self = this
axios.post('/contact/store', params)
.then(function(){
self.contact.name = '';
self.contact.email = '';
})
.catch(function(error){
console.log(error);
});
console.log(this.contact);
return;
}
}
}
</script>
In app.js file inside \resources\assets\js add the component
Vue.component('contacts', require('./components/Contacts.vue'));
Finally, call the contacts component inside your blade file.
<div class="container">
<div id="app">
<contacts></contacts>
</div>
</div>

How to get inputs before submiting and put it on textArea LARAVEL

my input for example :
<div class="form-group">
<label for="name">New Name Offers :</label>
<input name="newNameOffers" class="form-control" id="newNameOffers">
</div>
<div class="form-group">
<label for="">From Email :</label>
<input name="fromEmail" placeholder="Email" class="form-control" id="fromEmail">
</div>
How can i put it on text area ....
That my textArea :
<textarea class="form-control" name="HEADER" id="HEADER" rows="11">i need to dispay my values here <textarea>
(i need to put the values not the name of variable)
I have tried to make a simple form for you. You can modify it as you wish. For this, you need to take help of javascript or other similar front end technologies. However, if your requirement is just to take the value to back end then you can get both value $request->newNameOffers and $request->fromEmail then you can concatenate and store in your desired way.
function myFunction() {
var val1 = document.getElementById("newNameOffers").value;
var val2 = document.getElementById("fromEmail").value;
var res = val1 +' '+ val2;
document.getElementById("HEADER").innerHTML = res;
}
<!DOCTYPE html>
<html>
<body>
newNameOffers:<br>
<input name="newNameOffers" onChange="myFunction()" class="form-control" id="newNameOffers">
<br>
fromEmail:<br>
<input name="fromEmail" placeholder="Email" class="form-control" onChange="myFunction()" id="fromEmail">
<p>Click the button to alert the contents of the text area.</p>
<!-- <button type="button" onclick="myFunction()">Try it</button> -->
<br>
<textarea id="HEADER"></textarea>
<script>
</script>
</body>
</html>
Why do you want to put it using Laravel, You can do it in the front-end(JavaScript, JQuery, Vue.js, React) itself.

Laravel CSRF Field in Vue Component

I would like to ask how can I add the csrf_field() in my vue component. The error is
Property or method "csrfToken" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
Here's the code:
<script>
export default {
name: 'create',
data: function(){
return {
msg: ''
}
},
props:['test']
}
</script>
<template>
<div id="app">
<form action="#" method="POST">
{{csrfToken()}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" id="location" class="form-control">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" id="age" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
</form>
</div>
</template>
As I already wrote here, I would simply suggest to put this in your PHP file:
<script>
window.Laravel = <?php echo json_encode(['csrfToken' => csrf_token()]); ?>
</script>
This way you're able to easily import your csrfToken from the JS part (Vue in this case).
Moreover, if you insert this code in your PHP layout file, you can use the token by any component of your app, since window is a JS global variable.
Source: I got the trick from this post.
Laravel version 5 or later
First you need to store your CSRF token in a HTML meta tag in your header:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then you can add it to your script:
<script>
export default {
name: 'create',
data: function(){
return {
msg: '',
csrf: document.head.querySelector('meta[name="csrf-token"]').content
}
},
props:['test']
}
</script>
And in the template:
<template>
<div id="app">
<form action="#" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" id="location" class="form-control">
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="number" id="age" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<input type="hidden" name="_token" :value="csrf">
</form>
</div>
</template>
Try this:
<script>
export default {
name: 'create',
data: function(){
return {
msg: '',
csrf: window.Laravel.csrfToken
}
},
props:['test']
}
</script>
And in your markup just use
<input type="hidden" name="_token" :value="csrf" />
EDIT
Bit of a rabbit hole but, one great feature of Vue is that it can easily handle POST, PATCH, etc. requests using AJAX and the vue-resource extension. Instead of using a <form> here you can process this data using your Vue component. If you were to take this route, you can set default headers to send with each request no matter what method it is, so you can always send your CSRF token.
exports deafult{
http: {
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
}
}
if you look at the /resources/assets/js/bootstrap.js you will find these lines
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
I believe you are using axios for your requests. this means you need to add
<meta name="csrf-token" content="{{csrf_token}}">
in your <head> tag.
Came across this problem whilst building multiple forms in a vue v-for loop.
added to data;
csrf: document.head.querySelector('meta[name="csrf-token"]').content,
Added hidden form element
<input type="hidden" name="_token" :value="csrf" />
I think you need to write it like this:
{{ crsf_token() }}
and not like this:
{{ csrfToken() }}
If that doesn't work, maybe try this:
{!! csrf_token !!}

AJAX form not returning data when using input file

im experiencing a weird issue. I have this form basically it just sends data to another cfm file that processes the inputs and updates a database. Today ive added an input type="file" so to process EXIF data from it and extract GPS info. The result page will copy a div to the specified target div. All works fine, data gets extracted and updated, but the div with the response does not appear anymore. As soon as i remove the input="file" div target div gets updated. Seems a response header issue, but i have no idea how to fix it. Thanks.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
// bind form using ajaxForm
$('#sede-form').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
<cfoutput query="dett_cli">
<form id="sede-form" enctype="multipart/form-data" action="modifica_sede_response.cfm" method="post" class="form-inline">
<input type="hidden" name="codice" value="#url.codice#" />
<input type="hidden" name="id_sede" value="#url.id_sede#" />
... [other fields]...
<input type="hidden" name="sed_coordinate_o" value="#sed_coordinate#" class="input-large">
<div class="control-group">
<label class="control-label" for="sed_coordinate">JPG Coordinate GPS </label>
<div class="controls">
<div class="input-prepend">
<input type="file" name="sed_coordinate" id="sed_coordinate" class="input-large">
</div>
</div>
</div>
... [other fields]...
<!-- END div.row-fluid -->
<div class="form-actions">
<button type="reset" class="btn btn-danger"><i class="icon-repeat"></i> Resetta</button>
<button type="submit" class="btn btn-success"><i class="icon-ok"></i> Aggiorna</button>
<div id="htmlExampleTarget"></div>
</div>
</form>
</cfoutput>
Try putting the following back into your ajaxForm options.
iframe:true,
forceSync:true,

Resources