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.
Related
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/
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);
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.
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
html
<div contentEditable="true">testing....</div>
jQuery
$(document).ready(function(){
$('[contenteditable]').removeAttr('contenteditable');
});
above codes is fine and working. you can feel it here.
Now, try this
$('[contentEditable]').removeAttr('contentEditable');
// notice the CamelCase of the string contentEditable
in FF 3.6, it gives an error on the console
An invalid or illegal string was
specified" code: "12 elem[ name ]
= value;
and the div is still editable.
I suspected it was the jQuery selector, but is not. By further inspection, it was the argument passed on the .removeAttr('contentEditable');. It works when all small letters. So, I thought it should be all small letters. I'm curious so I tried adding CLass as an attribute and do .removeAttr('CLass');. But then it works without error.
So, how come contentEditable is giving me that error?
update
from Kobi, it seems that it actually accept any case except, contentEditable (I did try too).
CamelCase
This isn't about small letters, but about the exact casing. Any other casing than contentEditable works, for example: removeAttr('ConTentEditable');.
I can't find the exact source of the problem, I guess it's a Firefox restriction.
It seems jQuery sets the attribute to an empty string before removing it, which is what's causing the error. This seems to work better:
$('[contentEditable]').attr('contentEditable', false);
You could call it a bug, but really the framework is designed this way. removeAttr, along with other attr functions, points to jQuery.attr() to set the attribute's value. After setting the attribute to "", it then attempts to remove it. The code for attr() specifically checks to see if the given string is a property name on the object first using the in operator:
// If applicable, access the attribute via the DOM 0 way
if ( name in elem && notxml && !special ) {
(from jQuery 1.4, line 1452-1453)
Since you're supplying the camelCase property name, it uses that instead of elem.setAttribute(), which is specifically the cause of the problem. For any other case, name in elem would return false (because property names are case sensitive), which is why it's successful then. jQuery does this mostly to work around cross browser issues with setAttribute().
It looks like Firefox has a problem with setting the property to an empty string, unless you have the same problem in other browsers. You could try and file a bug either on the jQuery site or MDC.
contentEditable seams to be a special attribute:
http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#contenteditable
The contentEditable property (not attribute, since that isn't what attr() and friends usually deal with) expects a string value, one of "true", "false" and "inherit". I wouldn't use jQuery to turn off contentEditable, but I imagine the following would work:
$('[contenteditable]').attr("contentEditable", "false");
Or you could bypass jQuery for setting the actual contentEditable property:
$('[contenteditable]').each(function() {
this.contentEditable = "false";
});