jQuery nested phone number validation - javascript

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

Related

how to write a js script to make data import from a form error free

I have implemented a HTML webpage which has a form, now I want to add a script to it to load (import) form input given by user and do check if all of it is white spaces and if it is then give error message otherwise proceed. I want to achieve this using Javascript. I could not find the method to do so, I tried disabling the button until length of string is not equal to number of whitespaces, but that doesn't seems efficient.
This worked for me
document.addEventListener('DOMContentLoaded', () => {
// by default submit button is disabled
document.querySelector('#submit').disabled = true;
// Enable button only if there is required text in the input field
document.querySelector('#id1').onkeyup = () => {
var my_string = document.querySelector('#id1').value;
var spaceCount = (my_string.split(" ").length - 1);
if (document.querySelector('#id1').value.length != spaceCount)
document.querySelector('#submit').disabled = false;
else
document.querySelector('#submit').disabled = true;
};
});
You can use HTML5 validation See Link for more info
You can add attributes like required to your html. This also allows you to set custom error messages if the input is not valid.
In JS, you can check if($form.valid)
You can use jQuery to disable the submit button until its valid also.

Compare duplicate values of two select in materializecss framework

I have two select boxes and i dont want that the user choose the same value in both.
I've tried some solution proposed on stack, but the materialized select is different from "normal select" as contains the options in list item elements.
However, i came up with a solution, which is all but elegant, i know..im a novice with these things.
But its not working as i intended.
I want to create an additional method for jquery validation plugin, in the example on fiddle i've inserted an additional field to show the error placement.
I think is pretty simple, but i just can't figure out how to do it...
$.validator.addMethod("checksameval", function(value, element) {
return $('#pref1').val() == $('#pref2').val()
}, "Pref1 and Pref2 cant have same value!");
https://jsfiddle.net/L24otmaa/5/
edited with custom method (still not working..)
The problem with your solution is that the form will still be valid and therefore it will be possible to send it anyway.
You have to add a custom validation. The plug-in offers a callback where you can check whatever you want before you finally submit it.
This can be done by adding your validation to a custom submit handler
var isSameValue = function() {
var val1 = $('#pref1').val();
var val2 = $('#pref2').val();
if (val1 == val2) {
$customErrorDiv.text('error you cant select same value twice!!');
return true;
}
$customErrorDiv.text('');
return false;
}
// check also on runtime
$('.course').change( function() {
isSameValue();
});
$("#application").validate({
// check before submitting
submitHandler: function(form) {
if (isSameValue()) {
return;
}
// submit the form manually
form.submit();
}
});
Fiddle: https://jsfiddle.net/7uhkddrx/
Documentation: https://jqueryvalidation.org/validate/
Of course you would have to style this message according to your needs.
EDIT: By the way: currently your select boxes are not set to be required.
EDIT2: added checking on runtime

SYMFONY FORM isClicked() issue (depending Browser) when mixed with JavaScript - JQuery: event.preventDefault() and event.target.submit()

The goal:
I want on a Symfony FORM to have two submit buttons. 1st one would be used to validate the form, the 2nd submit button would be used to get away from the form.
By default the fields of the form use the required check before submitting, which means that prior to use the 2nd Submit, the required attributes need to be turned off on DOM <input>. I do that by using some JQuery, event.preventDefault(), I turn off the required on each <input> and then do an event.target.submit().
Then on my Symfony side I expect to catch the button that had been clicked by using the $form->has([button name])->isClicked() function.
The issue:
I have noticed that depending on the browser, the $form->has([button name])->isClicked() doesn't work if some JavaScript with event.preventDefault() and event.target.submit() had been used.
On chrome (Version 51.0.2704.103 m) I get (isClicked = 1 or true):
On firefox (Version 47.0) or Microsoft EDGE 25.* I get (isClicked = false):
The code:
The full code is at the following github.
Emphasis on the code:
In /src/AppBundle/Form/FormType.php you'll find, the code that manages the JavaScript to hold on the Submit, turnoff the required and resume the Submit:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field1',EmailType::class, array('label'=>'Form Field 1'))
->add('submit',SubmitType::class,array('label'=>'Submit Form'))
->add('get_away_from_form',SubmitType::class,array(
'label'=>'Get away from form',
'attr'=>array(
'onclick'=>'{
//IF THE USER CLICK THE NOT_SUBMIT BUTTON THE REQUIRED FIELD ARE DISABLED BEFORE THE SUBMIT HAPPENS
// Here is the part where are done (see GITHUB code for details):
////`event.preventDefault()`,
//// turn off the `required` on each `<input>`
//// and then do an `event.target.submit()`.
}'
)
));
}
In /src/AppBundle/Controller/DefaultController.php you'll find, the check on $form->get('get_away_from_form')->isClicked():
if($form->isSubmitted() && $form->has('get_away_from_form')){
if($form->get('get_away_from_form')->isClicked() == 1){
$isClicked = 'It works as expected: $form->get(get_away_from_form)->isClicked() = '.$form->get('get_away_from_form')->isClicked();
} else {
$isClicked = 'It DOESN\'T work as expected: $form->get(get_away_from_form)->isClicked() = '.$form->get('get_away_from_form')->isClicked();
}
}
Anyone has an idea?
Why are you using a submit button to get away from the form, instead of just using a link to another page ? It would avoid the need to bypass form validation
In such case one needs to use event.stopPropagation() instead of event.preventDefault().
And there is no need for the event.target.submit().
Now, my JS function associated to the onclick looks like this:
'onclick'=>'{
//IF THE USER CLICK THE NOT_SUBMIT BUTTON THE REQUIRED FIELD ARE DISABLED BEFORE THE SUBMIT HAPPENS
e= \'form\';
$(e).submit(
function(event){
event.stopPropagation();
}
);
function disableReq(e){
var disableReqDef = $.Deferred();
var disableReqDefProm = disableReqDef.promise();
requiredFields = $(e).find(\'[required="required"]\');
requiredFields.each(function(){
$(this).attr(\'required\',false);
});
disableReqDef.resolve();
return disableReqDefProm;
}
var dr = disableReq(e);
$.when(
e,
dr,
undefined
).done(function(e){
$(e).submit(function(event){});
});
}'
Why not use code like the following:
if ( $form->get('get_away_from_form')->isClicked() ){
return $this->redirectToRoute('detourRoute');
}
if ($form->isSubmitted() && $form->isValid()) {
...
Or is it that you MUST use javascript and/or JQuery in your code. My suggestion is simpler... This is only just a suggestion.

input validation vs. required to submit on multi-page forms

i have a multi-page form that i am trying to validate using jquery validate. the user has essentially 4 options: next, prev, save, submit.
save, next, and prev all save the current page to the form as a whole; submit is the same as save, but fires some additional workflow-related functions then heads off to another part of the site.
i need to validate the user input at all times. the jquery validate is working great. but... i need to have some fields set as required. because the form is saved at each step, the input needs to always be valid, but i don't need the required validation until the very end (on submit).
the form is building a dynamic list of validations specific to the page it is on, like:
$(document).ready(function() {
$("#ctl01").validate({ onsubmit: false });
$("#_Qn_0e868ebe").rules("add", { maxlength: 200 });
$("#_Qn_d69e75a4").rules("add", { number: true });
$("#_Qn_adffbdec").rules("add", { maxlength: 200 });
$("#_Qn_adffbdec").rules("add", { digits: true });
});
so now, for required fields, i've added a .isrequired class to them, and i've decoupled the <asp:linkbutton>s to fire this client script:
function FormIsValid(sender, ishardsubmit) {
var form = $("#ctl01");
form.validate();
if (form.valid()) {
//if (ishardsubmit) {
// if (!IsRequiredValid()) { return false; }
//}
__doPostBack(sender, '');
}
return;
}
this part (the input validation part) is working great so far. the part i commented out is the part that is working not so great. it fires this function, in which i was trying to dynamically add required validators and re-evaluate the form. i can see it hit the .each loop for each of my required fields, but it doesn't seem to be working since it passes true back, even when required fields are empty.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function (i, item) {
$(item).rules("add", { required: true });
});
form.validate();
return form.valid();
}
i toyed with the idea of dropping the .net required field validators in to do this part, but i want to, if possible, stick with a single solution. especially since this feels so close to working.
thoughts? help? thanks!
Your jQuery .each() method is constructed improperly.
You want to target the whole object in your iteration, not key/value pairs. So remove i, item from the function arguments and use $(this) as the target selector.
function IsRequiredValid() {
var $requiredgroup = $(".isrequired");
$requiredgroup.each(function() {
$(this).rules("add", { required: true });
});
// form.validate(); // remove this line -> 100% superfluous
return form.valid();
}
Regarding your form.validate() line in both functions: You cannot call .validate() more than once on the page. It's only meant to be called once to initialize the plugin on your form.
Calling it subsequent times will have no effect. Otherwise, we wouldn't need to use the .rules() method as we would simply call .validate() any time we need to change rules. However, this is definitely not the case.
Add a class to your required fields called something like: "SubmitRequired"
Implement two functions as follows:
function SaveClick(){
//ignore SubmitRequired on save (and any disabled fields)
$("form").validate({ ignore: ".SubmitRequired, [disabled]" });
if $("form").valid()
{
do something;
}
}
function SubmitClick(){
//ignore only disabled fields (if any))
$("form").validate({ ignore: "[disabled]" });
if $("form").valid()
{
do something;
}
}

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