Multipart jQuery validation - javascript

I'm trying to validate different parts of a form separately. Unfortunately, the form is generated by a CMS, so I'm limited in my manipulation.
I've tried creating an array of validate objects, using the current form section as an index. Ie:
//initialize validation
validators = [
$('#donation_amount').validate({ rules:{ amount: { required: true } } }),
$('#personal_information').validate({ rules:{ Street: { required: true } } })
];
and shifting through the sections like so:
$('#btn-next').click(function() {
//if validation is true, show next page
if (validators[curOrder].valid()) {
var old = $('.active');
var oldOrder = old.attr('data-order');
var newOrder = parseInt(oldOrder) + 1;
old.removeClass('active');
$("[data-order='" + newOrder + "']").addClass('active');
curOrder = newOrder;
}else{
console.log("invalid");
}
});
The validation, however, is always returning true.
Here's the page in question: https://salsa3.salsalabs.com/o/50388/p/salsa/donation/common/public/?donate_page_KEY=8461

Why are you even using .validate plugin when you are writing a little javascript yourself. On click, just check the value of the inputs (like $('#myInput').val().trim() == "") and show/hide the respective error div against each input.
Further, for multipart validation, validate only the required fields and continue what is supposed to.
$('#btn-next').click(function() {
var amountValid = $('#donation_amount').val().trim() == '' ? false : true;
var infoValid = $('#personal_information').val().trim() == '' ? false : true;
if (amountValid && infoValid) {
var old = $('.active');
var oldOrder = old.attr('data-order');
var newOrder = parseInt(oldOrder) + 1;
old.removeClass('active');
$("[data-order='" + newOrder + "']").addClass('active');
curOrder = newOrder;
}else{
console.log("invalid");
}
});

Related

How can I add validation to an Input field? Binding JSON model doesn't work

I try to learn SAPUI5 with Samples frpm Demo kit Input - Checked. I get an error message: oInput.getBinding is not a function
I have a simple input field xml:
<Label text="Name" required="false" width="60%" visible="true"/>
<Input id="nameInput" type="Text" enabled="true" visible="true" valueHelpOnly="false" required="true" width="60%" valueStateText="Name must not be empty." maxLength="0" value="{previewModel>/name}" change= "onChange"/>
and my controller:
_validateInput: function(oInput) {
var oView = this.getView().byId("nameInput");
oView.setModel(this.getView().getModel("previewModel"));
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var bValidationError = false;
try {
oBinding.getType().validateValue(oInput.getValue());
} catch (oException) {
sValueState = "Error";
bValidationError = true;
}
oInput.setValueState(sValueState);
return bValidationError;
},
/**
* Event handler for the continue button
*/
onContinue : function () {
// collect input controls
var that = this;
var oView = this.getView();
var aInputs =oView.byId("nameInput");
var bValidationError = false;
// check that inputs are not empty
// this does not happen during data binding as this is only triggered by changes
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
// output result
if (!bValidationError) {
MessageToast.show("The input is validated. You could now continue to the next screen");
} else {
MessageBox.alert("A validation error has occured. Complete your input first");
}
},
// onChange update valueState of input
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
Can someone explain to me how I can set the Model?
Your model is fine and correctly binded.
The problem in your code is here, in the onContinue function
jQuery.each(aInputs, function (i, oInput) {
bValidationError = that._validateInput(oInput) || bValidationError;
});
aInput is not an array, so your code is not iterating on an array element.
To quickly fix this, you can put parentheses around the declaration like this:
var aInputs = [
oView.byId("nameInput")
];
Also, you could remove the first two lines of the _validateInput method since they are useless...
Usually, we set the model once the view is loaded, not when the value is changed. For example, if you would like to set a JSONModel with the name "previewModel", you can do as mentioned below.
Note that onInit is called when the controller is initialized. If you bind the model properly as follows, then the oEvent.getSource().getBinding("value") will return the expected value.
onInit: function(){
var oView = this.getView().byId("nameInput");
oView.setModel(new sap.ui.model.json.JSONModel({
name : "HELLO"
}), "previewModel");
},
onChange: function(oEvent) {
var oInput = oEvent.getSource();
this._validateInput(oInput);
},
...
Also, for validating the input text, you can do the following:
_validateInput: function(oInput) {
var oBinding = oInput.getBinding("value");
var sValueState = "None";
var sValueStateText = "";
var bValidationError = false;
if(oBinding.getValue().length === 0){
sValueState = "Error";
sValueStateText = "Custom Error"
}
oInput.setValueState(sValueState);
if(sValueState === "Error"){
oInput.setValueStateText(sValueStateText);
}
return bValidationError;
},
Please note that the code above is not high quality and production ready as it's a quick response to this post :)

How to read a sublist data in netsuite?

I am new to suitescript. Openly telling I hardly wrote two scripts by seeing other scripts which are little bit easy.
My question is how can read a data from sublist and call other form.
Here is my requirement.
I want to read the item values data highlighted in yellow color
When I read that particular item in a variable I want to call the assemblyitem form in netsuite and get one value.
//Code
function userEventBeforeLoad(type, form, request)
{
nlapiLogExecution('DEBUG', 'This event is occured while ', type);
if(type == 'create' || type == 'copy' || type == 'edit')
{
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
//var itemfield = nlapiGetFieldValue('item')
//nlapiLogExecution('DEBUG','This value is = ',itemfield);
var formname = nlapiLoadRecord('itemreceipt',itemfield);
nlapiLogExecution('DEBUG','This value is = ',formname);
}
}
}
How can I proceed further?
I want to read that checkbox field value in the following image when i get the item value from above
I recommend looking at the "Sublist APIs" page in NetSuite's Help; it should describe many of the methods you'll be working with.
In particular you'll want to look at nlobjRecord.getLineItemValue().
Here's a video copmaring how to work with sublists in 1.0 versus 2.0: https://www.youtube.com/watch?v=n05OiKYDxhI
I have tried for my end and got succeed. Here is the answer.
function userEventBeforeLoad(type, form, request){
if(type=='copy'|| type =='edit' || type=='create'){
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
var itemcount = nlapiGetLineItemCount('item');
nlapiLogExecution('DEBUG','This value is = ',+itemcount);
for(var i=1;i<=itemcount;i++)
{
var itemvalue = nlapiGetLineItemValue('item','itemkey',i);
nlapiLogExecution('DEBUG','LineItemInternalID = ',itemvalue);
var itemrecord = nlapiLoadRecord('assemblyitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
if(itemrecord == null){
var itemrecord = nlapiLoadRecord('inventoryitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
}
var value = itemrecord.getFieldValue('custitem_mf_approved_for_dock_to_stock');
nlapiLogExecution('DEBUG',"Checkboxvalue = ",value);
if(value == 'F'){
nlapiSetLineItemValue('item','location',i,9);
nlapiSetLineItemDisabled ('item','location',false,i );
}
else{
nlapiSetLineItemValue('item','location',i,1);
nlapiSetLineItemDisabled ('item','location',true,i );
}
}
}
}
}

Microsoft Dynamics CRM 2011/2013

In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}

How to format jEditable field value after it cancels

I am trying to use the "onreset" option but I am having issues. I have a field that is meant for users to enter 10 numbers only. I want to make the 10 numbers display in a phone format ie. (310) 490-1235. So far I can do this, and the HTML of the field gets set to 3104901235 while the text is (310) 490-1235, but when a user cancels or goes to another field, the current field closes, and displays the HTML (3104901235) instead of the text (310) 490-1235.
I have a function set in the "onreset" option for it to set the text but it doesnt apply.
//Phone field
// Set the fields 10 digits to phone format
set_phone();
function isNumeric(value) {
if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
return true;
}
$('.edit-phone').editable('<?php echo base_url(); ?>home_resume/builder/ajax_save_field', {
onsubmit: function(settings, td) {
rm_class();
var input = $(td).find('input');
var original = input.val().trim();
if (isNumeric(original) && original.length == 10) {
$('#notification-saved').miniNotification({opacity: 1.0});
return true;
} else {
$('#notification-phone').miniNotification({opacity: 1.0});
input.css('background-color','#c00').css('color','#fff');
return false;
}
},
type : 'text',
cancel : 'Cancel',
onreset : function(value, settings){
$(this).closest("li").removeClass("active");
// Since the HTML is now just 10 digits, set it back to phone format with
set_phone();
},
style : 'display: inline',
select : 'true',
submit : 'OK',
event : "edit-phone",
indicator : '<img src="<?php echo base_url(); ?>themes/resume-builder/images/fb-indicator.gif">'
});
$(".edit-phone-trigger").on("click", function() {
strip_phone();
$(this).closest("li").addClass('active');
var edit_id = $(this).attr("id").split("-");
$('#' + edit_id[1]).trigger("edit-phone");
return false;
});
// Format the 10 digit phone number
function set_phone() {
var num = $("#7").text();
var num_1 = num.slice(0,3);
var num_2 = num.slice(3,6);
var num_3 = num.slice(6,11);
var new_num = "("+num_1+") "+num_2+"-"+num_3;
$("#7").text(new_num);
}
// Remove characters from phone number input
function strip_phone() {
var pnum = $("#7").text();
pnum = pnum.replace(/\(/g, "");
pnum = pnum.replace(/\)/g, "");
pnum = pnum.replace(/-/g, "");
pnum = pnum.replace(/\s/g, "");
$("#7").html(pnum);
}
You can try using the data and callback options for changing the way the text is displayed inside the input, this way you also avoid the need to use your custom event.
data will be called when the element is first clicked and can be used to alter the text before editing. Here you strip the phone to just numbers to be displayed on the input.
callback will run after after the form has been submitted. Here you format the submitted content to a phone number and change the text of the original element. (Inside function this refers to the original element)
$('.edit-phone').editable('<?php echo base_url();?>home_resume/builder/ajax_save_field', {
type : 'text',
cancel : 'Cancel',
style : 'display: inline',
select : 'true',
submit : 'OK',
event : 'click',
indicator : '<img src="<?php echo base_url(); ?>themes/resume-builder/images/fb-indicator.gif">',
data : function(value, settings) {
return strip_phone(value);
},
callback : function(value, settings){
$(this).text(set_phone(value));
}
onsubmit : function(settings, td) {
rm_class();
var input = $(td).find('input');
var original = input.val().trim();
if (isNumeric(original) && original.length == 10) {
$('#notification-saved').miniNotification({opacity: 1.0});
return true;
} else {
$('#notification-phone').miniNotification({opacity: 1.0});
input.css('background-color','#c00').css('color','#fff');
return false;
}
},
});
// Format the 10 digit phone number
function set_phone(text) {
var num = text;
var num_1 = num.slice(0,3);
var num_2 = num.slice(3,6);
var num_3 = num.slice(6,11);
var new_num = "("+num_1+") "+num_2+"-"+num_3;
return new_num;
}
// Remove characters from phone number input
function strip_phone(text) {
var pnum = text;
pnum = pnum.replace(/\(/g, "");
pnum = pnum.replace(/\)/g, "");
pnum = pnum.replace(/-/g, "");
pnum = pnum.replace(/\s/g, "");
return pnum;
}
Note that I updated your set_phone() and strip_phone() functions to return the value instead of setting it directly to the element so they can be called dynamically

Explanation of this JavaScript Code

I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone
I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me.
Here:
function tm_search_click() {
if (document.getElementById('tm').value == 'Enter your trademark') {
document.getElementById('tm').style.backgroundColor = '#fcc';
return false;
} else {
window.location = '?tm=' + escape(document.getElementById('tm').value);
return true;
}
}
function qs(a) {
a = a.replace(/[[]/, "\[").replace(/[]]/, "\]");
var b = "[\?&]" + a + "=([^&#]*)";
var c = new RegExp(b);
var d = c.exec(window.location.href);
return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ")
}
if (qs("tm") != "") {
tm_trademark = document.getElementById("tm").value = unescape(qs("tm"));
tm_partner = "migu2008";
tm_frame_width = 630;
tm_frame_height = "auto";
tm_trademark_country_code = "GB";
tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css";
document.getElementById("tmLoading").style.display = "block";
tm_on_search_result = function () {
document.getElementById("tmLoading").style.display = "none";
document.getElementById("tmLoaded").style.display = "block"
}
} else {
tm_search_method = "none"
}
That is all of it without the <script> tags.
Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page)
Page loads.
The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used.
User clicks something that triggers the tm_search_click
Script sets new URL for the page and browser starts loading that
Goto step 1.

Categories

Resources