Form validation using js - Laravel - javascript

I'm using Laravel
I have this form items
I get validation from database and I'm using jquery for validation
all inputs feild have name="element[{{$element->id}}]" (get id from database)
I'm trying different method to make validation but it doesn't work
#if($element->type =='text' && $element->is_depend_on=='0')
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="userName">{{$element->label}}</label>
<input id="userName" name="element[{{$element->id}}]" type="text"
class="form-control #if($element->validation=='required')required #endif" placeholder={{$element->placeholder}}>
#if($errors->has('element.'.$element->id))
<div class="error">{{ $errors->first('element.'.$element->id) }}</div>
#endif
</div>
</div>
</div>
#endif
#if($element->type =='textarea' &&$element->is_depend_on=='0')
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="userName">{{$element->label}}</label>
<textarea class="form-control #if($element->validation=='required')required #endif" name="element[{{$element->id}}]"
placeholder={{$element->placeholder}} *="" style="margin: 0px; width: 601px; height: 108px;" spellcheck="false" data-gramm="false"></textarea></div>
#if($errors->has('element.'.$element->id))
<div class="error">{{ $errors->first('element.'.$element->id) }}</div>
#endif
</div>
</div>
#endif
and here is my js code
var form = $("#order");
form.validate({
errorPlacement: function (error, element) {
error.insertBefore(element);
},
rules: {}
});
also I tried this code
$("#order").validate({
rules: {
},
messages: {
}
});
can anyone help me , or Do you have any suggestions ?

just use https://parsleyjs.org/ for form validation on your blade template. Very effective and has a lot of useful API and plugins. Rather than repeating same validation again and again you can make use of this little open source project.

Related

jQuery form validation after embedding Html with JS

I have a website developed within ASP.NET Core MVC (.NET6) + jQuery, Bootstrap. Due to some restrictions, some navigation pages must be embedded dynamically by non-typical way using Ajax request.
$.ajax({
url: link,
type: 'GET',
dataType: 'html',
headers: { 'X-Page-Request': 'true' },
success: function (data) {
var isFullPage = /<!DOCTYPE *html>/i.test(data);
if (!isFullPage) {
$("#contentContainer").empty().append($(data));
}
}
});
Some endpoints return partial views with already rendered HTML and JS code and this code embeds into pages after Ajax request using $("#contentContainer").empty().append($(data));
I need to validate the form and show validation outlines only after click on "Create" button, but validation is triggered even after a click on a bootstrap select element or "Cancel" button. I've already set all necessary options to the validator as default.
The thing is that if the code is originally on the page and doesn't integrate dynamically, form validation works as designed. But if I embed the same code using .append() and $.validator.unobtrusive.parse(), I have unexpected form validation after bootstrap select click or any button click.
Descried issues appear only in case when rendered HTML and JS code was added dynamically using .append(). As a result, elements with .btn class trigger form validation: all buttons, bootstrap select element etc. I need to prohibit this unexpected form validation and validate only using.valid().
Does anybody have any thoughts how to fix that? Thanks in advance!
P.S. I guess it's somehow related to the button element or .btn class.
Embedded code doesn't contain any special things except $.validator.unobtrusive.parse() and looks as usual.
<div id="userModal" class="modal fade" role="dialog" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="cl-modal-body modal-body">
<form class="form" id="user1Form">
<div class="row shift">
<div class="col-xs-12">
<div class="flex-align-center">
<label for="name" class="input-name-text-align-right input-name">* Name:</label>
<input for="name" class="form-control" id="userName" name="name" data-val="true" data-val-required="* This field is required." />
</div>
</div>
</div>
<div class="row shift">
<div class="col-xs-12">
<div class="flex-align-center">
<label for="countryId" class="input-name-text-align-right input-name">* Country:</label>
<select for="countryId" class="cl-select-form-control form-control" name="countryId" id="countryId1" data-val="true" data-val-required="* This field is required."></select>
</div>
</div>
</div>
</form>
</div>
<div class="cl-modal-footer">
<button type="button" class="btn cl-modal-button" data-dismiss="modal">Cancel</button>
<button type="button" id="userModalButton" class="btn btn-primary cl-modal-button">Save</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$.validator.unobtrusive.parse("#userForm");
initCountries();
openUserModal();
});
...
$('#userModalButton').click(function (e) {
if ($("#userForm").valid()) {
...
}
});
...
</script>

How to locate the dynamic input fields and pass values in protractor

Please some one help me to locate the dynamic elements and send the values to that elements using protractor.
Here is my purchaseInfo.html code snippet, where input fields are dynamically loading on the page:
<div class="row subpage-submit-flow">
<div class="col-md-12">
<!-- progress bar -->
<uib-progressbar value="45" class="in-progress"></uib-progressbar>
<!-- end progress bar -->
<div class="page-header">
<h2 id="purchaseInfo-header" translate="content.PURCHASE_INFO_HEADER"></h2>
<p id="purchaseInfo-reqFieldLbl" translate="content.PURCHASE_INFO_REQUIRED_FIELD_LABEL"></p>
</div>
<div class="row">
<div class="col-md-12">
<p ng-show="purchaseInfo.$invalid" class="error-message pull-right">
*Please complete all required fields.
</p>
</div>
</div>
<div class="clearfix"></div>
<div class="row">
<div ng-class="purchaseInfoCtrl.receiptImage ? 'col-md-6' : 'col-md-12'">
<form name="purchaseInfo" novalidate>
<div ng-if="webAttributes" class="row">
<div ng-repeat="webAttribute in webAttributes track by $index">
<div class="clearfix" ng-if="$index % 2 == 0"></div>
<div ng-class="purchaseInfoCtrl.receiptImage ? 'col-md-12' : 'col-md-6'">
<div ng-if="purchaseInfoCtrl.isTextField(webAttribute) || purchaseInfoCtrl.isCurrencyField(webAttribute)"
class="form-group">
<p class="noMargin"
ng-show="purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$viewValue || webAttribute.focused"
ng-class="(purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$invalid && purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$dirty) ? 'input-error-label' : (webAttribute.focused) ? 'activeFieldLabel' : 'inactiveFieldLabel'">
<span>{{ webAttribute.displayValue }}</span>
</p>
<input id="{{ webAttribute.name }}" border-color ng-if= "webAttribute.webAttributeType == 'C'" ng-focus="purchaseInfoCtrl.focus($event)"
ng-blur="purchaseInfoCtrl.blur($event)"
ng-class="purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$dirty && purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$invalid ? 'input-error' : ''"
class="noBorderTextBox" type="text" class="form-control noBorderTextBox" name="{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}"
ng-model="purchaseInfoCtrl.model.attributes[webAttribute.webAttributeIndex].value"
placeholder="{{ webAttribute.displayValue }}"
ng-required="webAttribute.mandatory"
ng-pattern="/^[^<%>\\\\]+$/">
<input id="{{ webAttribute.name }}" border-color ng-if= "webAttribute.webAttributeType == 'P'" ng-focus="purchaseInfoCtrl.focus($event)"
ng-blur="purchaseInfoCtrl.blur($event)"
ng-class="purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$dirty && purchaseInfo.{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}.$invalid ? 'input-error' : ''"
class="noBorderTextBox" type="text" class="form-control noBorderTextBox" name="{{webAttribute.webAttributeType}}{{webAttribute.webAttributeIndex}}"
ng-model="purchaseInfoCtrl.model.product.attributes[webAttribute.webAttributeIndex].value"
placeholder="{{ webAttribute.displayValue }}"
ng-required="webAttribute.mandatory"
ng-pattern="/^[^<%>\\\\]+$/">
</div>
I am following page object pattern and in my purchaseInfo-pageObject.js class, i have written this below function and calling this from the purchaseInfo_spec.j. Surprisingly, sendKeys is not working but dispalyed&sendvalues is getting printed in the console.Please help me. I will appreciate it. Thanks in advance.
this.inputFieldsAll = function (){
this.inputElems = element.all(by.repeater('webAttribute in webAttributes track by $index')).get(1);
if (this.inputElems.isDisplayed()){
this.inputElems.sendKeys('764763688888');
console.log('dispalyed&sendvalues');
}
this.inputElems.getText().then(function(val){
console.log('value: ',val);
});
First of all, there is a major problem in your current code:
if (this.inputElems.isDisplayed()) {
isDisplayed() returns a promise which is always "truthy", hence the condition is always true regardless of the real displayedness state.
The other problem is related to which element you are trying to send the keys to. Currently, you are sending the keys to the div element matching the repeater. Instead, you need to locate the inner input element(s):
var inputs = element.all(by.repeater('webAttribute in webAttributes')).get(1).all(by.tagName("input"));
inputs.first().sendKeys("764763688888");

Spring and jQuery validation: How to use localized strings?

Take this form as an example:
<form id="login_form" method="post" action="/rest/auth/auth">
<div id="login_email" class="row margin-top-50">
<div class="col-md-12" id="input_container">
<input id="login_email_input" class="input_edit input_edit_img_width" type="email" name="email" th:placeholder="#{label.common_email}"></input>
<img class="input_edit_img" src="/img/ic_login_user.png"></img>
</div>
</div>
<div id="login_password" class="row margin-top-15">
<div class="col-md-12" id="input_container">
<input id="login_password_input" class="input_edit input_edit_img_width" type="password" name="password" th:placeholder="#{label.common_password}"></input>
<img class="input_edit_img" src="/img/ic_login_pw.png"></img>
</div>
</div>
<div class="row margin-top-15">
<div class="col-md-12">
<div class="checkbox_square">
<input id="check_password_show" type="checkbox" value=""></input>
<label for="check_password_show"></label>
<span th:text="#{label.common_password_show}"></span>
</div>
</div>
</div>
<div class="row margin-top-15">
<div class="col-md-12">
<button id="login_submit" type="submit" class="btn btn-default btn-blue" th:text="#{label.login}"></button>
</div>
</div>
</form>
As you can see im using localized messages like th:placeholder="#{label.common_email}" for example.
I now want to use jQuery Validation and i really need to somehow use the localized strings from my messages.properties like something like this:
$("#login_form").validate({
rules: {
email: {
required: true,
email: true
},
password: {
required: true
/*minlength: 6,
maxlength: 20*/
}
},
messages: {
email: {
required: "#{label.input_missing_email}",
email: "#{label.input_missing_email_valid}"
},
password: {
required: "#{label.input_missing_password}",
minlength: "#{label.input_missing_password_valid}"
}
}
});
Is there any way how i can access my spring localization message from client side javascript? Or should i better use something different for validation if i have to use the localized strings?
You don't need to retrieve the your locale strings from your messages.properties at javascript level,
You can do this easily if you keep your locale string in HTML only,
Here what I will do:
HTML:
Make separate <span> or <div> after each input (in case you want
to show some msg after that element , some validation kind)
Keep all you locale string here at html in <span> and <div>
JS:
Just show/hide your respective <span> or <div> when jQuery validation fires for corresponding form inputs.
jQuery.i18n.properties is a lightweight jQuery plugin for providing internationalization to javascript from ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language and country codes.More
Suppose
label.delete.success =Successfully Deleted
label.delete.failure=Error in success
is your messages.properties properties file.
Then jQuery.i18n.prop(label.delete.success) returns Successfully Deleted from your javascript file.
Hope this helps.

How can I use the JQuery Validation Plugin to validate this form that have this specific constraint? [duplicate]

This question already has answers here:
jQuery Validate plugin, one out of two fields is required
(2 answers)
Closed 7 years ago.
I am pretty new in JQuery and I have the following problem related to a form validation.
So I think to not write the validator by myself but to use the JQuery Validation Plugin, this one: http://jqueryvalidation.org/
From what I have understand it provide me the built in required() method that make a specific field required (if the user don't insert a value for this field an error message is shown).
Ok...my problem is that in my form I have something like this:
<form method="post" action="consultazioneRicercaForm" id="consultazioneRicercaForm">
<div class="row">
<div class="col-md-4">
<label style="display: block;">Regioni:</label>
<select name="regioneSelezionata" id="selReg">
<option value="-">--SELEZIONARE UNA REGIONE--</option>
<option value="AB">ABRUZZO</option><option value="BA">BASILICATA</option><option value="CA">CAMPANIA</option><option value="CL">CALABRIA</option><option value="EE">REGIONE ESTERA</option><option value="EM">EMILIA ROMAGNA</option><option value="FR">FRIULI-VENEZIA GIULIA</option><option value="LA">LAZIO</option><option value="LI">LIGURIA</option><option value="LO">LOMBARDIA</option><option value="MA">MARCHE</option><option value="MO">MOLISE</option><option value="PI">PIEMONTE</option><option value="PU">PUGLIA</option><option value="SA">SARDEGNA</option><option value="SI">SICILIA</option><option value="TO">TOSCANA</option><option value="TR">TRENTINO-ALTO ADIGE</option><option value="UM">UMBRIA</option><option value="VA">VALLE D' AOSTA</option><option value="VE">VENETO</option>
</select>
</div>
<div class="col-md-4">
<label style="display: block;">Province:</label>
<select name="provinciaSelezionata" id="selProv"><option value="">--SELEZIONARE UNA PROVINCIA--</option></select>
</div>
<div class="col-md-4">
</div>
</div>
<div style="margin-top: 30px;" class="row">
<div class="col-md-4">
<label style="display: block;">Codice Meccanografico:</label>
<input type="text" value="" name="codMec" id="selCodMec">
</div>
<div class="col-md-4">
<label style="display: block;">Tipologia Progetto:</label>
<select name="tipologiaProgettoSelezionato" id="selTipologiaProgetto">
<option value="-">--TIPOLOGIA--</option>
<option value="WIFI">WIFI</option><option value="LIM">LIM</option><option value="Altro">Altro</option><option value="Classi 2.0">Classi 2.0</option><option value="Scuola 2.0">Scuola 2.0</option><option value="CSD">CSD</option>
</select>
</div>
<div class="col-md-4">
<label style="display: block;">Stato Progetto:</label>
<select name="statoProgettoSelezionato" id="selStatoProgetto">
<option value="-">--STATO PROGETTO--</option>
<option value="Da compilare">Da compilare</option><option value="In lavorazione">In lavorazione</option><option value="Da validare">Da validare</option><option value="Validato">Validato</option><option value="Rendicontato pregresso">Rendicontato pregresso</option>
</select>
</div>
</div>
<div style="margin-top: 30px;" class="row">
<div class="col-md-12">
<input type="submit" value="Cerca">
</div>
</div>
</form>
As you can see it contains some field of which those that have id="selReg" and id="selCodMec".
So my validation is focused only on the previous 2 fields and in particular the form can be considered valid if the field having id="selReg" OR the field having id="selCodMec" have a value setted. So if at least one of these 2 fields is valorized by the user my form is considered valid.
I think that in this case I can't use the required() method because it seems to me that the required() method is refered on a specific field and don't implement the previous logic.
How can I solve this problem? Can I use this JQuery Validation Plugin for my purpose?
Tnx
I use in one of my project the jQuery Validation as well.
Try to add a own validation rule:
$.validator.addMehtod('oneOrOther',function(value) {
if(!$("#selReg").val() && !$("#selCodMec").val())
return false;
else
return true;
});
Assign the validation to the field:
$("#consultazioneRicercaForm").validate({
...
rules: {
regioneSelezionata: {
oneOrOther: true
}
...
}
});
I hope, I understood your question correctly.

Meteor Accounts - Login forms change HTML remove dropdown JS

How do I modify Meteor's Accounts-ui to change the classes and the html tags rendered without re-writing all the accounts-ui logic?
For example I'd like to remove the "dropdown" behavior and just display the form directly in my page.
I read this answer but it doesn't go into detail - it just removes the default CSS. I'd like to go a bit deeper..
I figured this out for another answer, but thought I'd put it in here since it seems like a quicker way to get what you want.
Template.login.rendered = function()
{
Accounts._loginButtonsSession.set('dropdownVisible', true);
};
(Template.login should be Template.yourTemplateWithLoginButtons)
Styling
Remove accounts-ui
meteor remove accounts-ui
Add accounts-ui-unstyled & less
meteor add accounts-ui-unstyled
meteor add less
Finally, add the following file to your project directory & edit it to your viewing pleasure
https://github.com/meteor/meteor/blob/master/packages/accounts-ui/login_buttons.less
More customization
You can edit the accounts-ui package and edit html & js without starting from scratch:
Remove the accounts-ui-unstyled package and add the stuff in the dir below (except package.js & accounts_ui_tests.js) to your project's client dir, add accounts-urls and edit it to fine tune it to your spec.
https://github.com/meteor/meteor/tree/master/packages/accounts-ui-unstyled
Until meteor gives us a way to specify load order
Rename the following files so they load in the correct order
1accounts_ui.js
2login_buttons.html
3login_buttons_single.html
4login_buttons_dropdown.html
5login_buttons_dialogs.html
6login_buttons_session.js
7login_buttons.js
8login_buttons_single.js
9login_buttons_dropdown.js
login_buttons_dialogs.js
If all you want to do is remove the drop down behavior, then it would suffice to just add the accounts-ui-unstyled package and hide the components you don't want visible: e.g.:
.login-link-text { display: none; }
in your CSS to hide the Sign in link.
Here are the relevant id's and classes that you look into styling:
#forgot-password-link
#login-buttons
#login-buttons-password
#login-dropdown-list
#login-email
#login-email-label
#login-email-label-and-input
#login-password
#login-password-label
#login-password-label-and-input
#login-sign-in-link
#signup-link
.accounts-dialog
.additional-link
.additional-link-container
.login-button
.login-button-form-submit
.login-buttons-dropdown-align-left
.login-close-text-clear
.login-close-textClose
.login-form
.login-form-sign-in
.login-link-and-dropdown-list
.login-link-text
.login-password-form
Create your own html template similar to this below. Style it to your taste.
meteor add accounts-password accounts-ui
<template name="login">
<form class="login-form">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Login</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="email" placeholder="Email address">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="password" placeholder="password">
</div>
</div>
<div class="panel-footer">
<button type="submit" class="btn btn-danger btn-lg">Login</button>
</div>
</div>
</form>
</template>
You can now call Meteor.loginWithPassword in the template event like so:
Template.login.events({
'submit .login-form': function(e) {
e.preventDefault();
var email = e.target.email.value;
var password = e.target.password.value;
Meteor.loginWithPassword(email, password,function(error){
if(error) {
//do something if error occurred or
}else{
FlowRouter.go('/');
}
});
}
});
You can create another form for registration as well.
Just call Accounts.createUser(object, callback);
This answer is a bit coming late but might help.
Create your own html template similar to this below. Style it to your taste.
meteor add accounts-password accounts-ui
<template name="login">
<form class="login-form">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Login</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" id="email" placeholder="Email address">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" id="password" placeholder="password">
</div>
</div>
<div class="panel-footer">
<button type="submit" class="btn btn-danger btn-lg">Login</button>
</div>
</div>
</form>
</template>
You can now call Meteor.loginWithPassword in the template event like so:
Template.login.events({
'submit .login-form': function(e) {
e.preventDefault();
var email = e.target.email.value;
var password = e.target.password.value;
Meteor.loginWithPassword(email, password,function(error){
if(error) {
//do something if error occurred or
}else{
FlowRouter.go('/');
}
});
}
});
You can create another form for registration as well.
Just call Accounts.createUser(object, callback);

Categories