Formly input field validation - javascript

I am having an issue with validation messages appearing in an application. Here is the application demo:
https://jsfiddle.net/MrPolywhirl/yxrh3ujp/
I have tried adding validation configuration. This is straight out of the docs.
app.run(function(formlyValidationMessages) {
formlyValidationMessages.messages.required = 'to.label + " is required"';
formlyValidationMessages.messages.max = '"The max value allowed is " + to.max';
formlyValidationMessages.messages.min = '"The min value allowed is " + to.min';
formlyValidationMessages.addTemplateOptionValueMessage('pattern', 'patternValidationMessage', '', '', 'Invalid Input');
});
I have set min/max values on my field. The field does get validated correctly, but the message still does not appear.
Neither the pattern/patternValidationMessage nor the validation (config) function are working for the field. They do nothing and even with a valid pattern, the field still shows that it is invalid (highlighted red).
{
key: 'cooldown',
type: 'input',
templateOptions: {
type: 'number',
label: 'Cooldown (in seconds)',
min : 0,
max : 600,
required: true,
//pattern: /^[0-9]+$/,
//patternValidationMessage: '"Needs to match " + options.templateOptions.pattern'
},
defaultValue: 30,
//validation: {
// messages: {
// required: function ($viewValue, $modelValue, scope) {
// return scope.to.label + ' is required';
// }
// }
//},
}
Can I get some pointers as to why the message will not appear?

Carefully look at the way how formcontrol condition should be setup in error template( specially in ng-if part).
<script type="text/ng-template" id="error-messages.html">
<formly-transclude></formly-transclude>
<div ng-messages="fc.$error" ng-if="options.formControl.$invalid && options.formControl.$touched" class="error-messages">
<div ng-message="{{ ::name }}" ng-repeat="(name, message) in ::options.validation.messages" class="message">{{ message(fc.$viewValue, fc.$modelValue, this)}}</div>
</div>
</script>
Also the way you have written setWrapper method in app config looks messy, so I have removed the code to a separate template and pointed the template here.
Take a look at updated jsfiddle .

Related

I can't get Html.TextBoxFor value with JavaScript

I am facing a very interesting problem.
the control I use
<input id="DOSYA_NO" name="DOSYA_NO" class="form-control" />
I can get the input value with the code below.
$("#gelenevrakFoto").click(function () {
alert($('#DOSYA_NO').val());
});
but this way the input value is empty.
$("#gelenevrakFoto").fileinput({
uploadUrl: "/Dosya/Upload?policeId=" + $('#POLICE_ID').val() + "&Kategori=GELENEVRAK&dosyaNo=" + $('#DOSYA_NO').val(),
maxFileCount: 10,
showBrowse: true,
browseOnZoneClick: true
});
Please I would like you to help on the subject. Thanks.
Try using callback function
You can also set uploadUrl as a function callback which will return a
string. In that case, the function will get executed at runtime just
before every ajax call. This will enable you to set a dynamic upload
url based on runtime / dynamic conditions.
https://plugins.krajee.com/file-input/plugin-options#uploadUrl
$("#gelenevrakFoto").fileinput({
uploadUrl: function() {
let params = {
policeId: $('#POLICE_ID').val(),
dosyaNo: $('#DOSYA_NO').val(),
Kategori: 'GELENEVRAK'
};
return "/Dosya/Upload?" + $.param(params); // $.param for good practice
},
maxFileCount: 10,
showBrowse: true,
browseOnZoneClick: true
});

Javascript: If then statement not working in function

I'm building a personality-type quiz and having difficulty tailoring the results page as I'd like it to. The if statement, contained in the display_scenario function, isn't working. I want it to generate a different final message depending on the value of the countValue variable but it's not working. If you are able to help me understand why it's not working, I'd appreciate it.
The key pieces of code are below. It's also in place on Codepen: http://codepen.io/msummers40/pen/eZaePe
Essentially, the quiz:
- asks people a series of questions
- each answer has a numeric weight assigned to it
- this numeric weight is tallied in the countValue variable
- I want to use the countValue variable as a way to generate one of four final pages
I've tried to set up an if statement at the end of the quiz but it's just not working and I'm unsure of how to get this to work - it seems to be building the final view regardless of what's in the if statement.
If you are able to help, thank you.
<body>
<!-- QUIZ BEGINS -->
<div id="wrapper">
<h2 id="cyoaHeader">TITLE HERE<br><small>SUBHED</small></h2>
<div id="quizImage"> </div>
<div id="prompt"> </div>
<div id="options"> </div>
<div id="buildingStatus"> </div>
</div>
<div id="addLinks"> </div>
<!-- QUIZ ENDS -->
<script>
// JSON for quiz
// Contains the questions, images and variable to give answers weight/direction
var story = {
intro: {
prompt: 'You need to get up and out and get on with a big task - what song would propel you out of bed?',
quizImage: '<img id="quizImage" src="https://upload.wikimedia.org/wikipedia/commons/a/ab/Semi-nude_woman_getting_out_of_bed_(rbm-QP301M8-1887-265a~5).jpg"><br />',
options: [{
name: 'Song 4',
path: 'questionTwo',
addition: 4
}, {
name: 'Song 3',
path: 'questionTwo',
addition: 2
}, {
name: 'Song 2',
path: 'questionTwo',
addition: 3
}, {
name: 'Song 1',
path: 'questionTwo',
addition: 1
}]
},
questionTwo: {
prompt: 'Sentence.<br/><br/>Question 2?',
quizImage: '<img id="quizImage" src="http://www.allgifs.com/wp-content/uploads/2013/09/pancake.gif">',
options: [{
name: 'A',
path: 'result',
addition: 4
}, {
name: 'B',
path: 'result',
addition: 3
}, {
name: 'C',
path: 'result',
addition: 2
}, {
name: 'D',
path: 'result',
addition: 1
}]
},
result: {
prompt: 'This is the default statement on the results page. I need to make it tailored to the countValue variable',
quizImage: '<img id="quizImage" src="http://viralgifs.com/wp-content/uploads/2014/03/cat_did_u_forget.gif">',
options: [{
name: 'FINAL CTA',
path: 'intro',
addition: 0
}]
}
};
//establishing counter for weighted answer
var countValue = 0;
console.log(countValue);
var additionInt = 0;
console.log(additionInt);
// Option is an object with properties {name and path objects, addition array}
function display_scenario(options) { //value passed had been chosen_options
var option_name = options.name;
var option_path = options.path;
var additionInt = options.addition;
countValue += additionInt;
// countValue = (additionInt + countValue);
console.log(additionInt);
console.log(countValue);
var scenario = story[option_path];
// Clear the #prompt, #quizImage, #options, #addLinks, #buildingStatus divs before writing new ones in if statment below -- GROUP THESE IN A FUNCTION BEFORE GO LIVE
jQuery('#prompt').empty();
jQuery('#quizImage').empty();
jQuery('#options').empty();
jQuery('#addLinks').empty();
jQuery('#buildingStatus').empty();
// THIS IF ELSE STRUCTURE DOESN'T SEEM TO BE WORKING - I'M TRYING TO SET IT UP SO THAT IT DISPLAYS ONE OF FOUR OPTIONS, DEPENDING ON THE VALUE OF THE countValue VARIABLE. ATM ONLY THREE OPTIONS ARE IN PLACE; NONE ARE WORKING.
// Create a <p> to display what the user has chosen if option_name is not null and append it to the #prompt <div>
if (options.name != 'result') {
jQuery('<p>').html('<i>You selected <b>' + option_name + '</b></i><br><p>And the running total is ' + countValue + '</p>').appendTo('#buildingStatus');
// Append the scenario's prompt
jQuery('<p>').html(scenario.prompt).appendTo('#prompt');
// Appending an image
jQuery('<p>').html(scenario.quizImage).appendTo('#quizImage');
// Appending links in the addLinks div
jQuery('<div>').html(scenario.addLinks).appendTo('#addLinks');
} else if (options.name == 'result' && countValue<17) {
jQuery('<p>').html('<i>Yay! This option worked. You selected <b>' + option_name + '</b></i><br><p>And the running total is ' + countValue + '</p>').appendTo('#buildingStatus');
// Append the scenario's prompt
jQuery('<p>').html(scenario.prompt).appendTo('#prompt');
// Appending an image
jQuery('<p>').html(scenario.quizImage).appendTo('#quizImage');
// Appending links in the addLinks div
jQuery('<div>').html(scenario.addLinks).appendTo('#addLinks');
} else {
jQuery('<p>').html('<i>Yay! This option worked. You selected <b>' + option_name + '</b></i><br><p>And the running total is ' + countValue + '</p>').appendTo('#buildingStatus');
// Append the scenario's prompt
jQuery('<p>').html(scenario.prompt).appendTo('#prompt');
// Appending an image
jQuery('<p>').html(scenario.quizImage).appendTo('#quizImage');
// Appending links in the addLinks div
jQuery('<div>').html(scenario.addLinks).appendTo('#addLinks');
};
// Append the options into the #options <div>
// We want to loop through all the options and create buttons for each one. A regular for-loop would not suffice because adding a button is not asynchronous. We will create an asynchronous loop by using recursion
function add_option_button(index) {
if (index === scenario.options.length) {
// Base case
return;
}
var option = scenario.options[index];
// Create a <button> for this option and append it to the #options <div>
jQuery('<button>')
.html(option.name)
.click(function(e) {
// This is an onclick handler function. It decides what to do after the user has clicked on the button.
// First, prevent any default thing that the button is going to do, since we're specifying our own action for the button
e.preventDefault();
// We'll want to call display_scenario() with this option
display_scenario(option);
})
.appendTo('#options');
// Add the next option button
add_option_button(index + 1);
}
add_option_button(0);
}
// This function waits until the document is ready
jQuery(document).ready(function() {
// Start the quiz
display_scenario({
name: null,
path: 'intro',
addition: 0
});
});
</script>
</body>
</html>
I think you need to recalculate the sum whenever the user changes something, apart from displaying the scenarios everytime. Split the display_scenario function into one to display the options, and into separate logic to sum up all options choosen.

Shorthand property name are not supported by current Javascript version in PHPStorm

I have used Jquery getScript and generate html form by Javascript however I got
Shorthand property name are not supported by current Javascript version in PHPStorm but my function work as well.
Concern: Before I used PHP to generate html form within another PHP framework but I think I should not used Server script to do that I should use JS to do that but I don't know how is it going on and is it support all browser or not so please give me some idea of this technique because I not yet understand much more about suing DOM and its performance.
Security Concern: if I used Javascript to generate Html form as below script it will less security or bad performance or not?
Another hand if I keep this code inside of HTMl I will never got this errors types.
$(document).ready(function () {
returnTill('returnTill');
});
function returnTill(returnTill) {
var chief_opt = '';
var teller_opt = '';
$.ajax({
url:'/teller/return_till_data',
method:'get',
dataType:'json',
timeout:4000,
async: false,
success:function (data, status) {
$.each(data, function(ins, vals){
if(ins === 'chief') {
cheifs = data.chief;
for(var key in cheifs){
chief_opt += '<option value="'+vals[key].id+'"> '+vals[key].username+' / '+vals[key].account_no+' </option>';
}
}if(ins === 'teller') { /* Tellers*/
tellers = data.teller;
for(var key in tellers){
teller_opt = '<option value="'+vals[key].id+'"> '+vals[key].username+' / '+vals[key].account_no+' </option>';
}
loadModale({
idSelector: returnTill,
title: 'Return Till',
labels: ['From','To','Amount','Description'],
loadType:'returnTill',
forms: {
input: {
selection: {
from:{chief_opt,class:'form-control', name:'retn_chief', id:'retn_chief'},
to:{teller_opt, class:'form-control', name:'retn_teller', id:'retn_teller'},
},
Amount :{type: 'text', name: 'retn_amount', class: 'form-control', Id: 'retn_amount', placeholder: '', style: '', value:''},
token:{ type: 'hidden', name: '_token', class: 'form-control', Id: 'token', placeholder: '', style: '', value: '{{csrf_token()}}'},
},
textarea : {
description:{class:'form-control', name:'tran_descr', rows:10, id:'tran_descr'}
}
},script: [
'/theme/js/jquery.validate.min.js',
'/theme/js/bootstrap-datepicker/js/bootstrap-datepicker.js',
]
});
}
});
},error: errorCallback,
});
}
Errors:
I perform the following steps in Webstorm to solve the same problem, so it may also work in PHPStorm:
Go to Settings by pressing ALT + CNTRL + S
Click on "Languages and Frameworks"
Click on 'Javascript'
In the "Javascript language version" drop-down, select 'ECMAScript 6'.
Click 'OK'
Now re-open any *.js files you may have previously had open, and notice that the errors are no longer there.
Hope that helps someone.
You can fix it this way:
from:{chief_opt: chief_opt}
So, if you change your code to this:
from:{chief_opt: chief_opt, class:'form-control', name:'retn_chief', id:'retn_chief'},
to:{teller_opt: teller_opt, class:'form-control', name:'retn_teller', id:'retn_teller'},
You shouldn't get anymore the PHPStorm error.
Hope it helped or at least cleared a little bit. ;)
PHP STORM SOLUTION
The error is attributed to the version of your Javascript Setting in PHPSTORM
STEPS
Go to settings(preference on macbook)settings/preference and click
Expand the Languages and Frameworks by clicking it
click language & frameworks
Click Javascript and change the Javascript language version to the current or ECMAScript6 recommended.select ecmascript

Parse Markdown into HTML in JavaScript X-Editable field

I am using the jQuery X-Editable edit-in-place library on a field and the JavaScript Marked Markdown Parser library to try and convert Markdown strings into HTML.
The goal is to show HTL and when it turns into a textarea edit field, to then how the Markdown. The Markdown will be what is saved and loaded from the backend in the live app.
I have setup a JSFiddle demo for this functionality...
http://jsfiddle.net/jasondavis/bfrrzz8h/
If you view the demo and click to edit the Description text and paste in this Markdown string # Marked in browser\n\nRendered by **marked** and click save, it will then alert you the parsed markdown to HTML string. THe problem is it does not update the DOM to show that new HTML string.
Any help in this please?
Marked library - https://github.com/chjj/marked
X-Editable library - https://github.com/vitalets/x-editable/
JavaScript from my demo
$('#task-description-modal').editable({
type: 'textarea', // text|textarea|select|date|checklist
url: '/updatetask',
pk: 123,
toggle: 'click', // click|dblclick|mouseenter|manual
inputclass: 'task_description resizable',
highlight: '#F1FFE7',
mode: 'inline', // inline | popup
placement: 'top',
title: 'Enter Task Description',
validate: function(value) {
if ($.trim(value) === '') {
return 'Task Description is Required';
}
},
params: function(params) {
//Addition params in addition to the default: pk, name, value
return params;
},
success: function(response, newValue) {
if (!response.success) return response.msg;
}
});
$('#task-description-modal').on('save', function(e, params) {
// Parse Description Markdown into HTML
var markdownDescription = marked(params.newValue);
alert(markdownDescription);
$('#task-description-modal').html(markdownDescription);
//$('#task-description-modal').html('test');
});
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/updatetask',
responseTime: 400,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
You're injecting your compiled HTML into the element you're using to get markdown input. This is simply setting yourself up for failure: have two elements, one for markdown text, and one to show the result, and switch between the two.
For instance, the following code already makes things work fine:
HTML:
<div style="margin: 50px">
<span id="task-description-modal">Task Description text</span>
<div id="processed"></div>
</div>
JS:
$('#task-description-modal').on('save', function(e, params) {
var markdownDescription = marked(params.newValue);
$('#processed').html(markdownDescription);
});
You just need to make sure to only show the element you intend to be shown depending on what the user has just done. Hidden #task-description-modal until the user clicks on #processed, at which point you hide #processed and force .focus() on #task-description-modal? Perfect.

Changing JavaScript variable dynamically

This is my program skeleton http://jsfiddle.net/zhwzY/
$(document).ready(function(){
$("#btnSend").click(function(){
var option = {
'delay' : false,
'helpSpanDisplay' : 'help-block',
'disableSubmitBtn' : false
};
if($('#agree').is(':checked')){
form_input = 'input:not("#reason")';
}else{
form_input = 'input';
}
var metric = [
[ form_input, 'presence', 'Please fill this textbox!']
];
$("#frm").nod(metric, option);
});
});
From the snippet, I try to make variable "form_input" to switch to a new value depend on the checkbox. With this method, I can prevent NOD (validation plugins) from validating unecessary input. But the variable "form_input" is not changing to the new value upon updating.
Please help.
P/s : No external reference to the NOD library in jsFiddle.

Categories