Javascript populate form after validation - javascript

I am doing a form for my javascript class, and I am getting stuck on a certain portion of it. I have a separate validator javascript file and call the function on the html file. All the validation works if the form areas are not filled in. What I want to do is if the fields are left blank they will fail the validation and will insert a value into that field. Below are an example of the form field, javascript function in the html page, and the external validator js file.
call function in html head:
function formvalidation(thisform) {
with (thisform) {
if (textbox_validation(first_name,"Please enter your first name.")==false)
{first_name.blur(); return false;};
if (textbox_validation(business_name,"Please enter your business. Please enter N/A if
you do not have one.")==false) { business_name.focus(); return false;
business_name.value=="N/A";};
The external js validator:
function textbox_validation(entered, alertbox) {
with (entered) {
if (value==null || value=="") {
alert(alertbox);
return false;
}
else {
return true;
}
}
}
So the validator works and focuses on the empty fields, but for some of my fields I want them to fill themselves with a certain value if validation fails or if it isnt filled int. The business_name line of code is when I tried to make it work. Any help is much appreciated!

Ordinarilly, you wouldn't use alert, but would instead put error messages in a span or div either near the input or at the top (or bottom) of the form. Additionally (as mentioned by #Frits van Campen) it is generally bad practice to use with
Try something like this instead:
function textbox_validation(entered, errormsg) {
var errbox = document.getElementById(entered.id + '-errors'); // just to prevent writing it twice
// Note this requires the input to have an id, and the errer box's id to be the same with an '-errors' suffix.
// Instead of using with, just acces properties normally
if (!entered.value) { // The `!` "neggation" operater makes "falsy" values `true`
// "falsy" values include `false`, the empty string, `0`, `null`, `undefined`, `NaN` and a few others
// Put the error message in the DOM instead of alerting it
errbox.innerHTML = errormsg;
return false;
}
else {
// Wipe any previous error messages
errbox.innerHTML = '';
return true;
}
}
And for the form validator, again; let's not use with. But also, when attempting to assing "N/A" to the value, you've used the comparison operator instead of the assignment operator, and you've done it after returning:
function formvalidation(thisform) {
// just use the `!` "negation" operator
if (!textbox_validation(thisform.first_name,
"Please enter your first name."))
{
thisform.first_name.blur();
return false;
}
if (!textbox_validation(business_name,
"Please enter your business. Please enter N/A if you do not have one."))
{
thisform.business_name.focus();
thisform.business_name.value = "N/A"; // for assignment, use `=`. `==` and `===` are used for comparison
return false; // a return statement ends the function, make sure it's after anything you want to execute!
}
}

Use the DOM to set the placeholder for the fields. Like this.
var myInput = document.getElementById('input1');
myInput.placeholder = 'This validation has failed.';

Related

Update input value after validation

Iā€™m new to Vue.
I would like to know if it is possible to update the input value after running a custom validation in Vuelidate. I have an input field for postcode. I want to return the postcode with the correct format in case the user forgets to put a whitespace, and update the input field with the correct value, e.g.
user input = XXXXXX
returned output = XXX XXX
Sample code
export default {
...
validations: {
postcode: {
required,
maxLength: maxLength(10),
validatePostcode: (value) => {
const result = customValidators.validatePostcode(value);
if (result !== false) {
if (result !== value) {
// UPDATE THE INPUT VALUE HERE WITH THE CORRECT POSTCODE FORMAT
}
return true;
}
return false;
}
}
}
...
}
I changed the arrow function declaration to a function shorthand declaration. I'm now able to access the component object and change the input field value via the Vuelidate model. Thanks to this: https://github.com/vuelidate/vuelidate/issues/237 šŸ™‚

How to get value in Js of other field that is passed to widget? Odoo

I created a widget which fills some fields automatically. Basically I am checking some values from google maps geolocate and filling other fields depending on what those values are. Turned out I need to check one value that is already in my form. What happens at the moment I get only value that was saved before and if it changes I still get the old value. My question if how to get that value real-time?
My code is something like this:
var gmap_autocomplete = form_common.AbstractField.extend({
// functions such as start, init, on_ready...
setFields : function (fieldName, fieldValue) {
var not_vat_payer = this.view.datarecord[this.node.attrs.check_not_vat]);
// Here I get the value that I want of previous form save
// for example if value was true, I came here and triggered this
//widget I will get value true, but if I change it to false
// I will still get true value of previous save
}
});
My field with widget looks like this:
<field name="not_vat2"/>
<field name="autocomplete" class="autoc" widget="gmap_autocomplete" street="street"
city="city" zip="zip" country_id="country_id" lang="lang" invoice_lang="invoice_lang"
property_account_payable_id="property_account_payable_id"
property_account_receivable_id="property_account_receivable_id"
check_not_vat="not_vat2"/>
Found the solution which is really simple:
This will return field value which is in view no matter its stored in db or not.
this.field_manager.get_field_value('field_name');
exmple.js
Make changes something like..
var model_obj = new Model('model.name');
var gmap_autocomplete = form_common.AbstractField.extend({
// functions such as start, init, on_ready...
setFields : function (fieldName, fieldValue) {
var not_vat_payer = this.view.datarecord[this.node.attrs.check_not_vat]);
new_val = false;
model_obj.call('method_name',[new_val]).then(function(result){});
}
});
example.py
#api.model
def method_name(self,new_val):
//write code for change field value

How to set goog.ui.Autocomplete minimum input to 0

I would like the autocomplete to show the entire list when the input box gets focused (no input is given). Would also like the auto complete to match substrings without having to fiddle with private variables.
At the moment the code is:
autocomplete = goog.ui.ac.createSimpleAutoComplete(
gsa.Game.gameData.teams, team2, false);
matcher=autocomplete.getMatcher();
matcher.useSimilar_=true
autocomplete.setMatcher(matcher);
Similar matches work but have to set a private variable for that (no getter or setter available).
The other one I have not been able to find out; how to show all data when no input is given (like a smart select input). So when the textbox receives focus it'll show all data since there is no filter text given. These are basic things that one would like to configure but can't find it in the API documentation.
You need to create descendants of goog.ui.ac.AutoComplete, goog.ui.ac.ArrayMatcher and goog.ui.ac.InputHandler. Also you will directly create the instance of auto complete object instead of calling goog.ui.ac.createSimpleAutoComplete.
In goog.ui.ac.AutoComplete descendant you assign custom input handler and matcher.
goog.provide('my.ui.ac.AutoComplete');
goog.require('goog.ui.ac.Renderer');
goog.require('my.ui.ac.ArrayMatcher');
goog.require('my.ui.ac.InputHandler');
my.ui.ac.AutoComplete = function(data, input, opt_multi, opt_useSimilar) {
var renderer = new goog.ui.ac.Renderer();
var matcher = new my.ui.ac.ArrayMatcher(data, !opt_useSimilar);
var inputhandler = new my.ui.ac.InputHandler(null, null, !!opt_multi, 300);
goog.ui.ac.AutoComplete.call(this, matcher, renderer, inputhandler);
inputhandler.attachAutoComplete(this);
inputhandler.attachInputs(input);
};
goog.inherits(my.ui.ac.AutoComplete, goog.ui.ac.AutoComplete);
In goog.ui.ac.ArrayMatcher descendant you need to override getPrefixMatches() method, since the default behaviour discards empty strings. So if there is an empty string, we just return the first x rows from the data.
goog.provide('my.ui.ac.ArrayMatcher');
goog.require('goog.ui.ac.ArrayMatcher');
my.ui.ac.ArrayMatcher = function(rows, opt_noSimilar) {
goog.ui.ac.ArrayMatcher.call(this, rows, opt_noSimilar);
};
goog.inherits(my.ui.ac.ArrayMatcher, goog.ui.ac.ArrayMatcher);
my.ui.ac.ArrayMatcher.prototype.getPrefixMatches = function(token, maxMatches) {
if (token == '')
{
// for empty search string, return first maxMatches rows
return this.rows_.slice(0, maxMatches);
}
else
{
return goog.base(this, 'getPrefixMatches', token, maxMatches);
}
};
In goog.ui.ac.InputHandler descendant you need to override processFocus() method, and force to show the autocomplete popup. This can be done by calling update() method with first parameter set to true.
goog.provide('my.ui.ac.InputHandler');
goog.require('goog.ui.ac.InputHandler');
my.ui.ac.InputHandler = function(opt_separators, opt_literals, opt_multi, opt_throttleTime) {
goog.ui.ac.InputHandler.call(this, opt_separators, opt_literals, opt_multi, opt_throttleTime);
};
goog.inherits(my.ui.ac.InputHandler, goog.ui.ac.InputHandler);
my.ui.ac.InputHandler.prototype.processFocus = function(target) {
goog.base(this, 'processFocus', target);
// force the autocomplete popup to show
this.update(true);
};

ExtJS ComboBox validation returns unexpected result

I've just been working on a ExtJS script and I have a ComboBox which has
allowBlank = false
and
forceSelection = true
I have an item in the list which acts as a default message which has a display text
Please select...
and no value
''
When I run validate on the ComboBox I get true
No idea why?
According to the documentation when
allowBlank = false
the validation is forced to check for value.length > 0
So I have done my own test in the JS Console
>> if (thisForm.controlManager.controlArray[2].allowBlanks) { if (thisForm.controlManager.controlArray[2].length >= 0) { true; } false; } else { if (thisForm.controlManager.controlArray[2].length > 0) { true; } false; }
and it returned false
So I thought it might a bug in validate method so I tried doing this
>> thisForm.controlManager.controlArray[2].validateValue('')
and got this as a result true
Any one have any kind of idea of what I might be doing wrong or if anything else needs set to get this validate to return false when value is ''.
PS. I've also tried this
>> thisForm.controlManager.controlArray[2].validateValue(' ')
and got the correct result which is false. This made me very confused as I would normally expect '' and ' ' to return the same value in validation.
I know that a workaround would be to set my value to ' ' but I would rather get it working with ''.
Thanks
I just so happened to end up grappling with this same issue, and after some looking around, managed to find a solution which does not require overriding Extjs's standard functionality.
Basically, there is a 'validator' config option for descendents of Ext.form.field.Text which allows programmers to specify a custom validation function for a component (see here).
Basically, your validator function gets called at the start of getErrors() and is evaluated before the rest of the field's standard validation. The validator function takes one argument (the value) and must return either true if the value is valid or an error message string if it is not.
The following config ended up working for my case:
validator: function (value) {
return (value === '/*Your emptytext text*/') ? "blankText" : true;
}
You have to use the emptyText configuration
Ext have this code for validate fields:
validate : function(){
if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
this.clearInvalid();
return true;
}
return false;
}
and getRawValue is defined like this:
getRawValue : function(){
var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
if(v === this.emptyText){
v = '';
}
return v;
}
so, if the value is equal to the empty text, the returned value is ''

Custom jQuery Validation Method

I've got two input fields, email and email_confirm. The email field has the value of the users email from the database. I want to make sure if the user updates their email (both inputs have to have the same value) that they match, however, I can't use the defaul equalTo because email input always has a value. So I need to check if email_confirm is equalTo email IF the email value is different to the default value.
Here's the code I have, value seems to be empty always also.
$.validator.addMethod('myEqual', function (value, element, param){
return value == $(param).val();
}, 'Message');
Just add the below rule for email_confirm field,
equalTo : "#email" //Replace #email with the id the of the email field.
No need to add custom method for that.
if ($("#email").val() != theDefaultValue) {
if ($("#email").val() == $("#email_confirm")) {
// It's all good
} else {
// It's all bad
}
} else {
// It doesn't matter
}

Categories

Resources