Using javascript namespaces with ruby and sinatra - javascript

I'm trying to create some javascript validation for my web app and it's all going pretty well except I do not want my script to look for something to validate all the time.
Let's say I have two things I want to validate for but they do not occur on the same page. They are on '/page1' and 'page2' and I don't want my validator for page1 to run on page2.
That should be possible through object literals right?
Something like this:
var validations =
{
page1validation :
{
init : function()
{
// validation page 1
}
}
page2validation :
{
init : function()
{
// validation page 2
}
}
}
So I need to call these validation methods like validations.page1validation.init() and I guess I could do this with inline javascript in each haml view where I have a form that needs validation.
%form{:action => ""}
%input{:type => "text"}
%input{:type => "submit", :value => "save"}
:javascript
$(function() {
validations.page1validation.init();
});
But there must be a better solution - I just can't think of one right now. So what would you do to make sure the validator doesn't try to validate all the time?
Oh and the inline javascript won't work if I put the javascript at the bottom in my layout file...

The simplest way to do what you want is to make the forms different, either with a different id or class.
Then your validations can use that difference to "target" each form independently. You don't need the extra "namespace" with that approach. Instead, you do something like this.
$(function() {
page1validation();
page2validation();
});
function page1validation() {
var form = getElementById('form1'); // form1 is the first form
if(!form) then return;
// .. perform validations in form 1
}
function page2validation() {
var form = getElementById('form2');
if(!form) then return;
// .. perform validations in form 2
}
Also, I'd advice you to invest some time in learning a js library like jQuery. It provides some built-in methods that will make the code above much smaller.

Related

Changing YUI (or AlloyUI) method behaviour

I was trying to change _onFormReset method in YUI (or Alloy UI) - I think it is common JavaScript (OOP) thing, but I am a noob in JS OOP and YUI (been using some JQuery till now) - how can I change functionality of method (keeping other methods as they are)?
for example;
Currently method looks like:
_onFormReset: function(event) {
var instance = this;
instance.resetAllFields();
},
(src: http://alloyui.com/api/files/alloy-ui_src_aui-form-validator_js_aui-form-validator.js.html#l1192)
But I want it to be like:
_onFormReset: function(event) {
var instance = this;
instance.resetAllFields();
/* PSEUDO:
**a.) action is logged (ajax call to DB)
b.) all fields in form are reset (default behaviour) + form get's a new anti CSFR UID via ajax
c.) notification is shown (like that message in my example but let's say: Form reseted!)
d.) (Submit button reappears)**
...
*/
},
I tried something like:
/* trying to hijack thingZ */
var FormReset = Y.Component.create({
// component name
NAME : 'form-validator-reset',
EXTENDS : Y.Base,
// Base component's method which extends
prototype : {
_onFormReset: function(event) {
var instance = this;
instance.resetAllFields();
Y.one("#submitit").setHTML("<h4>Thanks, form submitted ok</h4>");
}
}
});
But with no success.
I looked at documentation and wasn't able to find a way, also it seems like I am missing OOP Javascript basics :(
Can somebody help me "catch the fish" :)
Trying to learn good (OOP) JavaScript for a long time, reading a lot online, but best way for me is learning by coding and now I am really stuck...
So my wish is to have something that I can use in all my forms for when reset button is clicked (in same way I would also change Submit) - OOP method - attached to default reset function, upgrading it in "my" way.
It looks like you're trying to tackle this the wrong way. Unless you're just doing this as an exercise in overriding a method you really shouldn't do that if all you're trying to do is print out a thank you.
Also if you're looking to thank the user for submitting you should be trying to do that when the user submits the form, not when the form is reset. To do this you'd subscribe a function to the 'submit' event of the form.
A.one("#my_form").on("submit", function() {
Y.one("#submitit").setHTML("<h4>Thanks, form submitted ok</h4>");
});
Ok, after rethinking it, I suppose preventDefault is ok for me (I will try to learn OOP JS with other cases :)).
This is (a n00by) solution:
add #resetit to reset button
add code:
var ressetterr = Y.one("#resetit");
Y.one(ressetterr).on("click", function(e){
console.log("resetit");
e.preventDefault();
});

jQuery nested phone number validation

Does anyone know how to use the jQuery validation plug-in while looping through inputs? The only way I know how to make the validation plug-in work is through a submit request. However, I am working on a multi-part form that validates on each step of the form and simply highlights required fields as the user moves through. I would like to add validation to this process as well, just not sure how to do it. Ideally, I'd like to validate more than just phone numbers, maybe email format and reg exp as well. Here the code I'm currently using:
function validateStep(step) {
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
if(valueLength == ''){
if($(this).hasClass('req')) {
hasError = true;
$this.addClass('hasError');
}
else
$this.removeClass('hasError');
} else {
$this.removeClass('hasError');
}
});
}
Any ideas?
The code in your question is not making a whole lot of sense to me. If you want to use the jQuery Validation plugin, then validation is handled automatically, you do not need to manually loop through any inputs.
As far as multi-step forms, there are many possible approaches. I prefer to use an individual form element for each step. Then I use the .valid() method to test the section before moving to the next. (Don't forget to first initialize the plugin; call .validate(), on all forms on DOM ready.)
Then on the last section, I use .serialize() on each form and concatenate them into a data query string to be submitted.
Something like this...
$(document).ready(function() {
$('#form1').validate({ // initialize form 1
// rules
});
$('#gotoStep2').on('click', function() { // go to step 2
if ($('#form1').valid()) {
// code to reveal step 2 and hide step 1
}
});
$('#form2').validate({ // initialize form 2
// rules
});
$('#gotoStep3').on('click', function() { // go to step 3
if ($('#form2').valid()) {
// code to reveal step 3 and hide step 2
}
});
$('#form3').validate({ initialize form 3
// rules,
submitHandler: function (form) {
// serialize and join data for all forms
var data = $('#form1').serialize() + '&' + $('#form2').serialize() + '&' + $(form).serialize()
// ajax submit
return false; // block regular form submit action
}
});
// there is no third click handler since the plugin takes care of this
// with the built-in submitHandler callback function on the last form.
});
Important to remember that my click handlers above are not using type="submit" buttons. These are regular buttons, either outside of the form tags or type="button".
Only the button on the very last form is a regular type="submit" button. That is because I am leveraging the plugin's built-in submitHandler callback function on only the very last form.
"Proof of Concept" DEMO: http://jsfiddle.net/j8vUt/
See this for reference: https://stackoverflow.com/a/19546698/594235

jQuery with remote validation does not wait for answer from server

I've noticed, that sometimes my validation code works wrong:
var $validator = $("#checkoutForm").validate();
...
if (!$validator.element($sameShippingAddress)) {
...
}
Debugging with Firebug showed, that sometimes $validator.element($sameShippingAddress) would return undefined (I guess it just does not wait till response is returned) and that would be assumed as false, even if element is valid.
If add code like this before if statement, everything works fine:
while (validator.element($sameShippingAddress) !== undefined) {
}
Question is if that is right solution and there's no better way to handle problem with validation plugin itself?
Update: I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Infinite while loop on validator variable is not a good choice. Instead use the code below that utilise Javascript timer. You can show animated processing/server response graphics after validate() method.
var validator = $('#resetpassword').validate({///your code...})
doTimer();
function timedCount()
{
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (validator === undefined)
{
timedCount();
}
}
if(validator==true)
$('#form').ajaxSubmit(options);
It's hard to tell how you are handling successful submissions or if you uses the css class to denoted required fields, but the following is how it's done in the demo for the plugin:
$.validator.setDefaults({
// code to be executed on submit
submitHandler: function() { alert("submitted, replace this with your server request");}
});
$().ready(function() {
// validate the comment form when it is submitted
// use css class .required for fields you want the validator to check
// if your form is valid then it is handled by the submitHandler
// if not the plugin displays error messages
$("#checkoutForm").validate();
//validate can take a block for custom validation and error messages
});
Hope this helps you find a solution and isn't just more of the same (also just realized this question is a year old, but I already wrote this so...)
Obiously, it is not the best solution. Instead add
if (!$validator.element($sameShippingAddress)) {
...
}
in the Ajax callback function.

Validation Group

Is it possible to get and control a validation group using javascript? I was able to validate ASPxHtmlEditor if empty or not, but i need to control the validation group. I'm using .net 2.0.
EDITS [04202011]
I need to make ASPxHtmlEditor a required field. I'm using an older version (10.1.6.0) of DevEx (can't update right now), but there is no validation settings for it. I used javascript to validate the editor
function validateEmptyEditor(html)
{
html = html.replace(' ', '');
html = html.replace('<br />', '');
if (html.length < 1)
{
return false;
}
else
{
return true;
}
}
I invoked the function in LostFocus of ASPxHtmlEditor.ClientSideEvents and is working properly. But my page uses validation group for saving. So I need to manipulate validation group when validateEmptyEditor is invoked. Is it possible to control validation group?
If I understand your task properly, you would like to know, whether the controls residing in the ValidationGroup are passing validation or not. If so, this can be done using the following js code:
var isValid = ASPxClientEdit.ValidateGroup("GroupName");
Does this help?

jQuery validate - adding a rule causes validation to fire

I have code like below to perform some conditional validation on fields in my form. The basic idea being that if something is entered in one field, then all the fields in this 'group' should be required.
jQuery.validator.addMethod('readingRequired', function (val, el) {
//Readings validation - if a reading or a date is entered, then they should all be ntered.
var $module = $(el).closest('tr');
return $module.find('.readingRequired:filled').length == 3;
});
//This allows us to apply the above rule using a CSS class.
jQuery.validator.addClassRules('readingRequired', {
'readingRequired': true
});
//This gets called on change of any of the textboxes within the group, passing in the
//parent tr and whether or not this is required.
function SetReadingValidation(parent) {
var inputs = parent.find('input');
var required = false;
if (parent.find('input:filled').length > 0) {
required = true;
}
if (required) {
inputs.addClass("readingRequired");
}
else {
inputs.removeClass("readingRequired");
}
}
//This is in the document.ready event:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
This works fine, and I've used pretty much the same code on other pages with success. The slight problem here is that when i enter a value into the first textbox and tab out of it, the validation fires and an error message is displayed. This doesn't happen on other pages with similar code, rather the validation waits until the form is first submitted. Does anybody have any idea why this might be happening?
Hmm. You know how it goes, post a question and then find a solution yourself. Not sure why this works exactly, but changing my binding from:
$("input.reading").change(function () {
SetReadingValidation($(this).closest("tr"));
});
to
$("input.reading").blur(function () {
SetReadingValidation($(this).closest("tr"));
});
Seems to have solved this issue. Would still appreciate being enlightened as to why that might be...

Categories