Validate input field and restore last valid value - javascript

I am trying to set validation on an input field using AngularJS directive, so that when the user types invalid value, the underlying model value changes to the last valid one. This is the contents of the directive:
// returns true/false
function validateValue(value) {
}
ngModelCtrl.$parsers.push(validateValue);
ngModelCtrl.$formatters.push(validateValue);
scope.$watch(attrs.checkValidName, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
So from my understanding, this code will basically run validateValue callback on every change of the input value and mark the input field with valid/invalid depending of the return value. This works great for basic validation, but the side effect of this in case the value is invalid, model value won't contain anything. I'm not sure how to change the code, so that when the value is invalid, the modal value actually contains the last valid value ?

Maybe you can overwrite $$writeModelToScope in the NgModelController. Only update the scope value if the controller is valid.
ngModelCtrl.$$$writeModelToScope = ngModelCtrl.$$writeModelToScope;
ngModelCtrl.$$writeModelToScope = function() {
if (ngModelCtrl.$valid) {
ngModelCtrl.$$$writeModelToScope();
}
};

Related

Procesmaker 4 setting default value with javascript code, how to access process variables

I am trying to set the default value of one of the form fields as a function of the value on another field. The javascript that I am using is:
if (Forma_pagament == "TRANSFERENCIA"){
return "1361";
}
else{
return "NA";
}
Forma_pagament is the Variable_name of another field in the same form. When previewing the form to test the javvascript I set the data input as:
{
"Forma_pagament": "TRANSFERENCIA"
}
For some reason the Value Forma_pagament does not get the value "TRANSFERENCIA" assigned so always the else statement is executed.
How should I reference other form variables in the javascript code to set the default value of a variable?

How do I detect whether or not an input with type=time has any values entered

I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.
However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.
In the below example, timeSelector is the input with type="time".
if (timeSelector.value == "") {
timeSelector.classList.add("empty");
} else {
timeSelector.classList.remove("empty");
}
Is there any way to detect this type of thing?
To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.
var checkInput = function() {
var value = this.value
var isValid = this.checkValidity()
if (!this.value.length && isValid) {
console.log('empty');
} else if (!this.value.length && !isValid) {
console.log('invalid time entered')
} else {
console.log('valid time entered')
}
}
var input = document.querySelector("input")
input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)
<input type="time" />
Per the specification on Input Elements with type time ( HTML Spec ) :
The value attribute, if specified and not empty, must have a value that is a valid time string.
If the value of the element is not a valid time string, then set it to the empty string instead.
This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.
You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.
The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.
By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">
The only way to possibly get around the lack of a changing value is to set a default value as below:
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("change");
<input type="time" value="00:00">
However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.
You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.
Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.

How to capture previous value of optionset field onchange?

I have an optionset field in an entity, I want to fire a JavaScript method on this field change. I want to capture the old value of the field on the change. I've got a solution which gets the old value on form load, but this doesn't work on multiple changes.
This has to be solved by our own code implementation. Store the attribute value on form load in a variable, keep the new value in that variable on every change, so you can use that in onChange handler. At the end of business validation inside handler put that new value in variable if success or revert to old value if failed.
var previousValue;
function onFormLoad(){
previousValue = formContext.getAttribute("fieldname").getValue();
}
function onFieldChange(){
if(myBusinessValidationSucceeds){
previousValue = formContext.getAttribute("fieldname").getValue();
}
}
Idea 1 and Idea 2

Show form if input field has data or else dont show

I am dynamically adding text to the input field from facebook signup data, and then populating these data to the form field which has a display:none property. After getting all the data the form should show as in display:block. But that is not working. the code seems to be working on console but not on the browser.
I am checking if the input field is filled then show the form or else no.
Here is the jsfiddle. http://jsfiddle.net/kqHmR/1/
if ($("#firstname").val() == $("#firstname").val(dataCollection.first_name)) {
$("#profileEdit").hide();
} else {
$("#profileEdit").show();
}
What is wrong with it? It is supposed to show me the form when there is something in the input fields but it's not showing .
Couldn't you just check if dataCollection.first_name is empty?
Here's a one-liner
$("#profileEdit").toggle(dataCollection.first_name.length);
Reference: http://api.jquery.com/toggle/
Explanation: .toggle() can accept a boolean. true = show, false = hide.
If a string's .length is zero, it evaluates to false, thus passing false into .toggle(). Vice versa.
In case you really want to check the input field's value instead, then:
$("#profileEdit").toggle( $.trim( $("#firstname").val() ).length );
Translated in English would be: Get me the value of firstname, trim it, and give me the length of that string, then pass it into .toggle()
.val() when called with an argument, sets the value and returns the jQuery object it was called on (to facilitate chaining). It does not return the value as such, unlike when called without arguments.
This means your if condition
if ($("#firstname").val() == $("#firstname").val(dataCollection.first_name)) {
will always fail as the RHS is not the newly set value but the jQuery object $("#firstname") itself.

Generic way to get the value of an input regardless of type

I'm trying to write a generic function I can use with the jquery validation plugin that will make a field required based on the value of another field. Here's what I want to happen:
If Field 1's value is in a specified array of values (currently testing with "No", "n/a", and "0"), or is empty, do nothing. Otherwise, make Field 2 required.
Getting the value of Field 1 is the issue. I had no problem figuring this out with a text-type or <select> input, but I'm trying to get it to work with radios and having difficulty. Here is an excerpt from my code:
var value = $('[name="option"]').val(),
empty = ['no', '', 'n/a', '0'];
// If the input is not "empty", make the additional field required
if ($.inArray(value.toLowerCase(), empty) < 0) { // returns -1 if not found
required = true;
} else {
required = false;
}
This works for everything I need it to except radios, because it seems to read the value of the first radio, regardless of if it was checked or not.
The field that will trigger the "required" will either be one of the various text inputs (text, url, email, etc.), a <select>, or a single choice set of radios. No multiple choice. I'll be passing this function as a parameter to required in my jquery validation config for each field I want it to apply to. The name attribute of the "other" field that gets evaluated will be available to it.
Here's my demo so far, kind of ugly but there are notes: http://jsfiddle.net/uUdX2/3/
I've tried a bunch of different ways using is(':checked') and the :checked selector, but they have all failed. I removed them from the demo because they didn't work.
What do I need to get this working with radios and text-type or select inputs, without knowing which kind of input it will be?
Try this
var value = $('[name="option"]');
var type = value.attr("type");
if(type && type.toLowerCase() == 'radio')
value = value.filter(":checked").val();
else
value = value.val();
Working demo
Something like this:
var value = $('[type="radio"][name="option"]:checked, [type!="radio"][name="option"]', form).val() || '0'
Quite similar to Shankar's but does it all in the selector.
http://jsfiddle.net/infernalbadger/uUdX2/8/
It's not working when nothing is selected. Not sure what you want it to do when that happens?

Categories

Resources