Debug jQuery form validation - javascript

I have a form that submits to a url using the action attribute <form action='/example/url'>. It uses the jQuery validation plugin.
jQuery("form#page-0").validate({
ignore: ':hidden'
,rules: {"product_id_page-0":{"required":true},"name_f":{"required":true,"regex":["^[^=:<>{}()\"]+$",""]},"name_l":{"required":true,"regex":["^[^=:<>{}()\"]+$",""]},"email":{"required":true,"remote":{"url":"\/premium\/ajax?do=check_uniq_email&_url=L3ByZW1pdW0vbG9naW4\/YW1lbWJlcl9yZWRpcmVjdF91cmw9JTJGcHJlbWl1bSUyRnNpZ251cC5waHA="}},"login":{"required":true,"rangelength":["6","32"],"regex":["^([0-9a-zA-Z_][0-9a-zA-Z_ ]+[0-9a-zA-Z_]|[0-9a-zA-Z_]+)$",""],"remote":{"url":"\/premium\/ajax?do=check_uniq_login"}},"pass":{"required":true,"rangelength":["6","32"]},"_pass":{"required":true}}
,messages: {"product_id_page-0":{"required":"Please choose a membership type"},"name_f":{"required":"Please enter your First Name","regex":"Please enter your First Name"},"name_l":{"required":"Please enter your Last Name","regex":"Please enter your Last Name"},"email":{"required":"Please enter valid Email","remote":"--wrong email--"},"login":{"required":"Please enter valid Username. It must contain at least 6 characters","rangelength":"Please enter valid Username. It must contain at least 6 characters","regex":"Username contains invalid characters - please use digits, letters or spaces","remote":"--wrong login--"},"pass":{"required":"Please enter Password","rangelength":"Password must contain at least 6 letters or digits"},"_pass":{"required":"This field is required"}}
//,debug : true
,errorPlacement: function(error, element) {
error.appendTo( element.parent());
}
,submitHandler: function(form, event){form.submit();}
// custom validate js code start
,errorElement: "span"
// custom validate js code end
});
The problem is that sometimes the form submits to the url before the validator fires. I'm suspicious of submitHandler: function(form, event){form.submit();} because I don't understand what the event parameter is doing. In the documentation for jquery validation there's no mention of a second parameter.
Any suggestions for debugging the form are also welcome. Variables to log or other ways to view what's happening. I did set debug:true but it doesn't seem to spit any errors to the console.

The problem is that sometimes the form submits to the url before the validator fires.
It might be because you've specified a non-existant rule. There is no such rule/method called regex. However, there is one called pattern contained within the additional-methods.js file. This is the root cause of your problems. Once the required rule is satisfied, the plugin attempts to evaluate the regex rule and chokes.
I'm suspicious of submitHandler: function(form, event){form.submit();} because I don't understand what the event parameter is doing. In the documentation for jquery validation there's no mention of a second parameter.
If you don't understand what it's doing and it's not in the docs, then why did you put the event argument into your code?
The documentation is correct, there is no second argument. However, having the additional arguments is merely superfluous and will not break anything.
You employ a very unusual code formatting style that makes it difficult to read and troubleshoot.
,submitHandler: function(form, event){form.submit();}
There is no second argument for this callback, so you can remove event.
Since you only have form.submit() within your submitHandler, it's not doing anything different from the default. In other words, remove the entire submitHandler, and after validation the form will submit to the action attribute as per the default.
NOTES:
ignore: ":hidden" is the default behavior, so you don't need to specify it.
It's not necessary to enclose the rule names within quotes.
DEMO: http://jsfiddle.net/1e82p64f/

Related

jQuery rules add mask

Good day,
I am support an project that develop by other team.
I saw some jQuery code that I am not really understand what the code is doing, I plan to amend on it but at first I need to know what it want to do first.
Here is the code:
$(function(){
$(':input[name=country]').rules('add', {
required: true,
mask: /^[a-zA-Z0-9 ]+$/
});
});
I am suspecting it is mask method, for example which is:
$(':input[name=country]').mask("0000-0000"); // this is work
But I try to run it but it fail, hitting error:
Cannot read property 'call' of jquery.validate.min.js:16 undefined
Any one know what is the code trying to do?
The .rules() method is part of the jQuery Validate plugin and has absolutely nothing to do with the .mask() method which is part of another plugin. This code is trying to dynamically add form validation rules to an input element with name="country".
$(':input[name=country]').rules('add', {
required: true,
mask: /^[a-zA-Z0-9 ]+$/. // <- there is no such rule called 'mask': REMOVE THIS LINE
});
The error is because jQuery Validate is looking for a rule called mask where there is no "mask" rule in this plugin.
Your only options are:
remove all references to this nonexistent rule, OR
create a custom rule called mask using the .addMethod() method
That code appears to be using the jQuery Validate plugin to create a validation rule that the value is required and must consist of only letters, numbers or spaces.
The validation rule is applied to any input, textarea, select, or button element that has a name property with the value of country. I suspect the problem is that you don't have one of these fields in your document.

How would I use javascript to validate an e-mail with output on the DOM?

Basically I created a form in html and when things are input properly it simply goes to google.com. Right now I have completed the first few fields but I am unsure of how I would make it recognize if the input that was put in and did not include an # sign or a . some point after it.
I created a fiddle as I was having trouble getting some of the longer of my lines of code to be in-line.
Click here for the fiddle Example
You have a few options depending on how thorougly you want to validate.
email.indexOf('#') >= 0
checks that there is an # at all in the email. See http://jsfiddle.net/27f1h6ws/ for a version of your fiddle with it added.
A more thorough way would be to check it with regex. You can do it extremely simple just checking the general structure of the email input, or extremely thorough check for all valid characters, depending on how crucial the validation is. See this link or the answers in this question for more information.
You can use HTML5 properties like :
pattern attribute which contains a regexp
set your input type to email
If you want to do it with JavaScript, use a regexp also and use the test() method to verify it.
Add this
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);

jQuery validator gives error when a form element contains id with some special symbols. 'Unrecognized expression'

I have a form with some elements that use ids wich special symbols like this:
id="$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[#type='qualification' and #position='prefix'][1]cb"
I have a function getEscapedID(id) that I use to escape a problematic characters when I need to find an element using jquery selector:
var input = $("#"+getEscapedID(id)).
This is not a problem - when I try it, I get the exact needed element. But calling input.valid(); gives me an error:
Error: Syntax error, unrecognized expression: label[for='$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[#type='qualification' and #position='prefix'][1]cb']
EDIT:
My question is whether it is possible to do something about it. If not, then I will consider simplifying ids.
The problem was that I used perhaps old jquery.validate.min.js script. When I tried the one from here, it works:
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js
Eventually the form's ids were changed because it was not valid according to http://validator.w3.org, so I doubt the problem was primarily in the plugin.

mootools form validator accept blank and email validation

I am trying to allow Blank inputs on my form but also validate an email if ever the user inputs one, i already changed the regex several times with the ones that i find here in stackoverflow that allows blank input but all of them doesn't work
here is the original code:
['validate-email', {
errorMsg: Form.Validator.getMsg.pass('email'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]\.?){0,63}[a-z0-9!#$%&'*+\/=?^_`{|}~-]#(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\])$/i).test(element.get('value'));
}
}],
how can i allow my mootools form validator to accept blanks but also verify email if there is any input?
Direct Source:
http://mootools.net/docs/more/Forms/Form.Validator
I see two options.
Option 1
Remove the required class from the input element. That will accept an empty value but check/validate if not empty. Try it here.
Option 2
The one you already have :)
I normally use this regex:
/^[a-z0-9._%-]+#[a-z0-9.-]+\.[a-z]{2,4}$/i
Found also this one. Anyway, it works; check this demo.
Email validation regex is so clumsy... Does mootools support validation functions?
Anyway, you can take your regex and create a bit more clumsy one: original-regex|^$, which will accept empty string

How to display HTML5 validation if inputElement.validity.valid == false?

So I have a form, but I don't need to be submitting the information to the server just yet... What I need, is to just run the fields through the HTML5 built-in validation conditions (such as email, etc.), and if true, just execute a specific function...
So far, I've come up with this...
function checkform()
{
var /* all the elements in the form here */
if (inputElement.validity.valid == 'false')
{
/* Submit the form,
this will cause a validation error,
and HTML5 will save the day... */
} else
{
navigateNextStep();
}
}
That's the logic I've come up with so far, and its a little backhanded because I'm submitting KNOWING that there's an invalid value, hence triggering the validation prompts...
My only problem with the above logic, is that I have about, 7-8 input elements, and I find the option of doing the following rather, 'dirty':
var inputs = document.getElementsByTagName("INPUT");
if (!inputs[0].validity.valid && !inputs[1].validity.valid && ...)
Ideas?
You can just call formEl.checkValidity()... This will return a boolean indicating whether or not the whole form is valid, and throw appropriate invalid events otherwise.
The spec
A brief JSFiddle to play with
I'm not sure how you're expecting submitting the form to trigger the browser's validation UI, though. Calling formEl.submit() seems to result in a submission regardless of the validation state. This is noted at the bottom of The H5F project page, which says:
Safari 5, Chrome 4-6 and Opera 9.6+ all block form submission until all form control validation
constraints are met.
Opera 9.6+ upon form submission will focus to the first invalid field
and bring up a UI block indicating
that it is invalid.
Safari 5.0.1, and Chrome 7 have removed form submission blocking if a
form is invalid, most likely due to
legacy forms now not submitting on
older sites.
Ok, so this is awkward... Thanks to Domenic, and good ol' Google, I came across an alternative solution...
I ran a for loop, checking if each of the input elements were valid or not through the imputElement.validity.valid method, which returned a boolean value...
For every element that was valid, I incremented a variable by 1, and included a conditional statement in the loop to check if the variable had been incremented enough to execute the navigation function...
If there was an invalid field, the if statement would never execute, and (here's the fun part) the browser would validate the fields anyways, pop up saying which fields were broken and needed user correction... :-)
The For Loop...
for (i=0;i<8;i++)
{
if (inputs[i].validity.valid)
hg++;
}
if (hg==8)
skimregform();
You can programmatically trigger the checking of each field in your form, even if you set event.preventDefault() function.
document.forms["form_id_name"].reportValidity();

Categories