I'm having trouble getting the Jquery Validation to work with the following rules.
I have the field masked with SSN format, the validation must not allow submission of this information without it being a complete SSN. I have a working regex function that rejects non SSNs. I need it to not allow blank submissions as well (the mask is only applied if the field is onFocus). And last but not least, the field is NOT required if another checkbox is checked (#noSSN).
I've added a JSfiddle page to help: http://jsfiddle.net/B2UpW/3/
It appears to be working a bit different on the fiddle page. Hope this helps!
Edit: I've yet to receive any responses.. curious if there is any confusion about my question? Any suggestions to help find some assistance is welcome!
$("#ssn").mask("999-99-9999");
$.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value !== param;
}, "Please choose a value!");
$("#applicantForm").validate({
rules: {
ssn: {
notEqual: "___-__-____",
required: {
depends: function(element) {
return ($("#ssn").val() == ""
|| isValidSSN($("#ssn").val())
|| $("#noSSN:unchecked"));
}
}
}
},
messages: {
ssn: 'Please enter a social security number.'
}
});
function isValidSSN(value) {
var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
if (!re.test(value)) { return false; }
var temp = value;
if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
if (temp.substring(0, 3) == "000") { return false; }
if (temp.substring(3, 5) == "00") { return false; }
if (temp.substring(5, 9) == "0000") { return false; }
return true;
}
Website owners, please stop using the piece of code from jammypeach or Stephen S. above. Some valid SSNs are rejected by their regexp.
See http://www.socialsecurity.gov/employer/randomization.html
Previously unassigned area numbers were introduced for assignment
SSNs can start with "773" and above since June 2011, before that thread was created.
Please replace ([0-6]\d{2}|7[0-6]\d|77[0-2]) with \d{3} - now I have to go to the bank in person because of you ;-)
You just needed to add a check to see if the checkbox was, er, checked.
See this updated fiddle, around line 9 (or line 2 in the code below) where you check if the SSN is valid:
$('#submitApplication').live('click', function() {
if ($('#noneSSN').is(':checked'))
{
alert("SUCCESS");
}
else
{
var isValid = $("#applicantForm").valid();
if (isValid) {
alert("SUCCESS");
}
}
return false;
});
It will now allow a submit if the box is checked, otherwise it will demand a correct SSN.
It's not very clear what is not working exactly...
I see a few things anyway:
What is notEqual? Is it a method you added ? There is an method called pattern in the additionnal methods script proposed along with the plugin.
What is the purpose of your depends ? Add a rule required to check the value is not empty and add a rule like isValidSSN: true to execute your own SSN validation.
Only use the depends (or required: function(element) { return $("#noSSN").is(":unchecked"); }) to apply the rules when the checkbox is not checked.
Hope this helps, d.
Related
Currently I am trying to write a code for validation for my site contact info, and I am stuck for 3 hours now on a probably some small problem, but I just can't figure it out.
The problem I have appears in second IF element inside else element, I want to make regex search for numbers [/d] and whitespace [/s] in selected string, but my code always sees only one rule, and ignores the other one.
I guess the mistake is that i didn't write it well, but I can't figure out how. Please give me some pointers where am I making mistake.
if (sFirstname == null || sFirstname == "") {
alert("First name must be filled out");
return false;
}
else {
if (/\d/, /\s/i.test(sFirstname)){
alert("Only Letters can be used in First name")
return false;
}
else {
alert("true")
return true;
}
}
There are many small thing I would like to change:
!sFisrtname will go true as long as sFirstname is not falsy ("", 0,
null, undefined, ...)
Use else if ... instead of else { if ... }.
The statement /\d/, /\s/i.test(...) will be evaluated to:
/\d/,
/\s/i.test(...)
Same as:
var a = /\d/;
var b = /\s/i;
a, (b.test(...))
What you want is properly /[\d\s]/.test(...) which will go true if there is a
digit or a space in sFirstname. You might consider changing the logic op-in
instead of op-out, eg: /[^a-zA-Z]/.test(...). Allow only a-z and A-Z
I made the function return the error instead of alerting it:
console.log(checkFirstName('John')); // "" (no error)
console.log(checkFirstName('John 42')); // "Only a-z can be used in first name"
This can also be used in an if statement:
var error = checkFirstName('John');
if (error) {
alert(error);
}
else {
alert('Everything is fine!');
}
And the function:
function checkFirstName(sFirstname) {
if (!sFirstname) {
return 'First name must be filled out';
}
else if (/[\d\s]/.test(sFirstname)) {
return 'Only letters can be used in first name';
}
else {
return "";
}
}
Please test it like this in your "if" condition, inside else. This regular expression will test only for alphabetic, not for numeric or blank space.
var regx = /[^a-zA-Z]+/;
regx.test(firstname);
change your IF statement like below
if (/\d|\s/i.test(sFirstname))
I need to create a code in HTML/Javascript that will allow a user to enter an answer to a maths question and then the site needs to validate whether that answer is correct.
Been playing around for a few hours and researched the web but not found anything close.
Any help is appreciated!!
You could use javascript for validation,
Look at this example.
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
checking if value of a textfield is integer in javascript
Javascript validation
function isInteger(number) {
var getVal = parseInt(number);
if (number.length == 0 || getVal == Number.NaN || getVal <= 0) {
return false;
}
return true;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
I am trying to use this javascript to check for a valid email, but what I don't need it to do is check to see if the field is blank in the form in case someone doesn't have an email address (don't ask).
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address.")==false)
{email.focus();return false;}
}
}
I tried to adjust the apos<1 to less than 1 or nothing at all and that didn't seem to work.
Just check whether it is empty, and otherwise apply your email regex/validation function on it.
Also, you should a) not use with and b) not alert from the test function.
function test_email(address) {
var atpos = address.indexOf("#"),
dotpos = address.lastIndexOf(".");
if (atpos < 1) // "#" at position 0 or not found (-1)
return false;
if (dotpos-atpos < 2) // last "." before position 2 or not found (-1)
return false;
if (atpos > dotpos) // last "." before the "#"
return false;
return true;
}
function validate_form(thisform) {
var input = thisform.email;
if (input.value) // != ""
if (!test_email(input.value)) {
alert("Not a valid e-mail address.");
email.focus();
return false;
}
}
A regular expression is probably the best approach, and a previous question has a great regular expression to use, though there are more complex and complete ones available. Validate email address in JavaScript?
Taking that regular expression and fitting into your code, you'd have a function looking something like this
function validate_email(field,alerttxt) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(field)) {
return true;
} else {
alert(alerttxt);
return false;
}
}
I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":
function checkforNumber()
{
if (isNaN(sInput || dInput || pInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
Am I using this function incorrectly? Is there something wrong with the syntax?
Thanks
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please reset the form.");
}
also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.
var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))
This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.
First of all apologise for creating my third Javascript question in as many days - I'm really trying to push myself in this field on this project, and feel my skills are developing at a fairly good rate thanks to my research and your fantastic help on here, particularly redsuqare!!
I've got a table where people can enter times, and have a mask in place where it'll check that the input is in the format 99:99 - which is great, but ideally I want to limit it to be no more than 23:59!
Here's the code I have at the moment, cobbled together the best I can, but unsurprisingly doesn't work...
$.each($('#hoursavailable tr td :checkbox'), function() {
var $this = $(elem); // cache the object
var $row = $this.closest('tr'); // find the nearest table row
if($this.is(':checked')) {
// do nothing!
} else {
$row.each(':text'),function() {
var splittime = $(this).split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
}
}
});
Could also be worth noting that there are two inputs per row/tr - it'd be absolutely ideal if I could somehow compare the two, to ensure that the first one is before the second, but appreciate that could be even more beyond me than the current stuff :(
Thanks
This may be what you are looking for-
http://www.the-art-of-web.com/javascript/validate-date/
I think all you need is the following change since your doing an each around the text inputs so you need to get the value out and split that.
$row.find(':text').each(function() {
var splittime = $(this).val().split(":");
if(splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date'); return false;
}
});
However to save yourself re-inventing the wheel why not look into the validate plugin where you can configure regex expressions to deal with data validation.
Although I do appreciate hand rolling is also a good learning curve.
You're going mad with your eaches when you really only need one
This ought to get you going with a few caveats as detailed below.
$("#hoursavailable :checked").each(function() {
var splittime = $(this).parents("tr").find(":text").val().split(":");
if (splittime[0] > 22 || splittime[1] > 58) {
alert('please enter a valid date');
return false;
}
});
I've assumed here that you only have one text box (hence .find(":text") on the parent. You could consider adding a class, but bear in mind that class selectors are slow.
There is no validation here, so you might want to add a little more, however the premise works.
Synthesis from different methods to check for max & format together.
var timeFieldValue = $(this).val();
re = /^\d{1,2}:\d{2}([ap]m)?$/;
if(timeFieldValue != '' && !timeFieldValue.match(re)) {
alert("Invalid time format: " + timeFieldValue);
$(this).focus();
return false;
}
var splittime = timeFieldValue.split(":");
if(splittime[0] > 23 || splittime[1] > 59) {
alert('Please enter a valid time');
return false;
}