How does jQuery Validation setups the validation message? - javascript

I wrote an additional method for jquery validation plugin that checks if a given value meets the length requirements defined along with the validation process.
So the method looks like this:
jQuery.validator.addMethod("exactLength", function(value, element, param){
var len = value.length;
if ($.isArray(param)){
if (param.indexOf(len) !== -1){
return true;
} else {
return false;
}
} else {
if (param != len){
return false;
} else {
return true;
}
}
}, jQuery.format("Value must have {0} characters"));
It works but the only problem is that message sent to the user doesn't meet my needs. The reason why is because one field might have more than 1 valid length.
A bank code can have 8 or 11 digits.
So, if I define the options below I expect the following output in case of error:
"Please, the value must have 8 or 11 digits."
{
"options":{
"rules": {
"inputx": {
"required": true,
"exactLength": [8,11]
}
}
}
}
But I want more flexibility because i can have 2 values defined as valid lengths, "Please, the value must have 8, 11, xxx or 23 digits"
Or i can basic field where the input must have only 1 specific length "please, the value must have 8 digits"
So, inside the method is it possible to tell want should be passed to the message?
EDIT:
Added full solution based on Arun P Johny answer
jQuery.validator.addMethod("exactLength", function(value, element, param){
var len = value.length;
if ($.isArray(param)){
if (param.indexOf(len) !== -1){
return true;
} else {
return false;
}
} else {
if (param != len){
return false;
} else {
return true;
}
}
}, function(param, element){
var str = "";
if ($.isArray(param)){
var paramLen = param.length,
lastParamValue = param[ paramLen - 1];
if (paramLen == 2){
str = param[0];
} else {
for(var i = 0; i< paramLen - 1; i++){
if (i == paramLen - 1){
str += ',' + param[i];
} else {
if (i == 0)
str += param[0];
else
str += ',' + param[i];
}
}
}
return jQuery.format("Value must have {0} or {1} characters", str, lastParamValue );
} else {
return jQuery.format("Value must have {0} characters", param )
}
});

The message option can be a function so
jQuery.validator.addMethod("exactLength", function (value, element, param) {
var len = value.length;
if ($.isArray(param)) {
if (param.indexOf(len) !== -1) {
return true;
} else {
return false;
}
} else {
if (param != len) {
return false;
} else {
return true;
}
}
}, function (param, element) {
//you can customize the string generation here, params refers to the array passed to the rule
return "Value must have " + param.join(',') + " characters"
});
Demo: Fiddle

Related

Combining 2 IF/ELSE statements (validation)

I am trying to combine 2 IF/Else statements to create one validation function. This is my code for the 2 separate validations:
function validateCarsMin(v){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
return '1B cannot contain a value if CW is entered';
}
} else return true
}
function validateRateLoc3(v){
if (v != ''){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
return 'This Value is not valid';
}}
}
I did not know if there was a best practice for this and it so, what would it be?
Thanks for the help on the last question I had.
Change the functions to return either true or false. You can push the msgs to an array to be used later.
var errorMsgs = [];
function validateCarsMin(){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
errorMsgs.push('1B cannot contain a value if CW is entered');
return false;
}
} else{
return true;
}
}
function validateRateLoc3(){
if(tfRateLoc3.getValue() < tfRateLoc4.getValue()){
return true;
} else {
errorMsgs.push('This Value is not valid');
return false;
}};
}
function validateForm(){
var isValid = false;
isValid = validateCarsMin();
isValid = (!isValid) ? isValid:validateRateLoc3();
return isValid;
}
Note I removed the v parameter because it seemed irrelevant. It is not used in the first function and it creates a syntax error in the second.

I am having problems getting my form to validate or submit [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
My form does not seem to be validating or submitting. It was submitting and validating before, but the Jquery error messages were not all displaying at the same time so I had to edit the code, and now it is not submitting or validating at all.
Here is my JS:
function validateUserName(user)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
return "You Left the Username field Emptyyy";
}
else if (uLength <4 || uLength > 11)
{
return "The Username must be between 4 and 11 characters";
}
else if (illegalChars.test(u))
{
return "The Username contains illegal charectors men!";
}
else
{
return "";
}
}
function validatePassword(pwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
return "You left the password field empty";
}
else if (pLength < 6 || pLength > 20)
{
return "Your password must be between 6 and 20 characters in length";
}
else if (p != cP)
{
return "The passwords do not match!"
}
else
{
return "";
}
}
function validateEmail(email)
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
return "You left the email field blank!";
}
else if (e.match(illegalChars))
{
return "ILEGAL CHARECTORS DETECTED EXTERMINATE";
}
else
{
return "";
}
}
function validateFirstName(fname)
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
return "First Name has a max of 20 characters";
}
else if (illegalChars.test(f))
{
return "Numbers,letter and underscores in first name only";
}
else
{
return "";
}
}
function validateLastName(lName)
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
return "Last Name has a max of 100 characters";
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only";
}
else
{
return "";
}
}
function validateForm()
{
/*
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
*/
var error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
error += "\n"+validateEmail();
error += "\n" + validateFirstName();
error += "\n" + validateLastName();
if(error === ""){
return true;
}
else{
$("#ErrorUser").text(error);
$("#ErrorEmail").text(error);
$("#ErrorFname").text(error);
$("#ErrorPassword1").text(error);
$("#ErrorLname").text(error);
return false;
}
}
$('#your-form').submit(validateForm);
Fiddle: http://jsfiddle.net/cyKgD/
You had few errors in your code.
The validateForm() is never being called
Line 174: Should be else if (illegalChars.test(l))
Line 113: Closing bracket missing
This fiddle seems to be working now, http://jsfiddle.net/u5565/
Make sure that jQuery is included in your page. The line of code
$(function() {
$('#your-form').submit(function() {
return validateForm();
});
});
tells jQuery to validate the form when it is submitted.
In your fiddle, you forgot method="POST" on the form tag
<form name = "NewUser" id = "your-form" method="POST">

Validate form function jump to error?

I have a form with a validation script that works perfectly. I would however like the form to jump to the fields that doesn't validate or display the name of the fields in the error message.
The code I use to validate is:
else
{
var valid = document.formvalidator.isValid(f);
}
if (flag == 0 || valid == true) {
f.check.value = '<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('There was an error with the fields..');
return false;
}
return true;
How can I get the alert to name the fields that need to be filled in correctly or jump to the specific field?
Edited ----------
Hi,
Thanks for help so far. I'm very new to JS. The form is in a component of Joomla.
The full function that validates the form is
function validateForm(f){
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){
var flag = 0;
for (var i=0;i < f.elements.length; i++) {
el = f.elements[i];
if ($(el).hasClass('required')) {
var idz= $(el).getProperty('id');
if(document.getElementById(idz)){
if (!document.getElementById(idz).value) {
document.formvalidator.handleResponse(false, el);
flag = flag + 1;
}
}
}
}
}
else {
var valid = document.formvalidator.isValid(f);
}
if(flag == 0 || valid == true){
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('<?php echo JText::_('JBJOBS_FIEDS_HIGHLIGHTED_RED_COMPULSORY'); ?>');
return false;
}
return true;
}
External js file:
var JFormValidator = new Class(
{
initialize : function() {
this.handlers = Object();
this.custom = Object();
this.setHandler("username", function(b) {
regex = new RegExp("[<|>|\"|'|%|;|(|)|&]", "i");
return !regex.test(b)
});
this.setHandler("password", function(b) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(b)
});
this.setHandler('passverify',
function (value) {
return ($('password').value == value);
}
); // added March 2011
this.setHandler("numeric", function(b) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(b)
});
this
.setHandler(
"email",
function(b) {
regex = /^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(b)
});
var a = $$("form.form-validate");
a.each(function(b) {
this.attachToForm(b)
}, this)
},
setHandler : function(b, c, a) {
a = (a == "") ? true : a;
this.handlers[b] = {
enabled : a,
exec : c
}
},
attachToForm : function(a) {
a.getElements("input,textarea,select")
.each(
function(b) {
if (($(b).get("tag") == "input" || $(b)
.get("tag") == "button")
&& $(b).get("type") == "submit") {
if (b.hasClass("validate")) {
b.onclick = function() {
return document.formvalidator
.isValid(this.form)
}
}
} else {
b.addEvent("blur", function() {
return document.formvalidator
.validate(this)
})
}
})
},
validate : function(c) {
c = $(c);
if (c.get("disabled")) {
this.handleResponse(true, c);
return true
}
if (c.hasClass("required")) {
if (c.get("tag") == "fieldset"
&& (c.hasClass("radio") || c.hasClass("checkboxes"))) {
for ( var a = 0;; a++) {
if (document.id(c.get("id") + a)) {
if (document.id(c.get("id") + a).checked) {
break
}
} else {
this.handleResponse(false, c);
return false
}
}
} else {
if (!(c.get("value"))) {
this.handleResponse(false, c);
return false
}
}
}
var b = (c.className && c.className
.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? c.className
.match(/validate-([a-zA-Z0-9\_\-]+)/)[1]
: "";
if (b == "") {
this.handleResponse(true, c);
return true
}
if ((b) && (b != "none") && (this.handlers[b])
&& c.get("value")) {
if (this.handlers[b].exec(c.get("value")) != true) {
this.handleResponse(false, c);
return false
}
}
this.handleResponse(true, c);
return true
},
isValid : function(c) {
var b = true;
var d = c.getElements("fieldset").concat($A(c.elements));
for ( var a = 0; a < d.length; a++) {
if (this.validate(d[a]) == false) {
b = false
}
}
new Hash(this.custom).each(function(e) {
if (e.exec() != true) {
b = false
}
});
return b
},
handleResponse : function(b, a) {
if (!(a.labelref)) {
var c = $$("label");
c.each(function(d) {
if (d.get("for") == a.get("id")) {
a.labelref = d
}
})
}
if (b == false) {
a.addClass("invalid");
a.set("aria-invalid", "true");
if (a.labelref) {
document.id(a.labelref).addClass("invalid");
document.id(a.labelref).set("aria-invalid", "true");
}
} else {
a.removeClass("invalid");
a.set("aria-invalid", "false");
if (a.labelref) {
document.id(a.labelref).removeClass("invalid");
document.id(a.labelref).set("aria-invalid", "false");
}
}
}
});
document.formvalidator = null;
window.addEvent("domready", function() {
document.formvalidator = new JFormValidator()
});
Where would I edit the code as some of you have answered below?
with jquery js library, scroll to element (id selector or class)
<p class="error">There was a problem with this element.</p>
This gets passed to the ScrollTo plugin in the following way.
$.scrollTo($('p.error:1'));
see source
Using jQuery's .each, loop over the fields. On every iteration the item that is being invesitigated will be under the this variable.
Therefore, this.id gives the id of the element you're looking for. Store these to collect all the incorrect fields, then highlight them or print their names in a message.
Keep in mind, this is the basic idea, I cannot give an actual answer until you show the code that handles the form.
Kind regards,
D.
You can have your isValid routine return the error message instead of returning a boolean.
In isValid, you can build up the error message to include the field names with errors.
Instead of checking "valid == true", you will check "errorMessage.length == 0".
If you want to focus on an error field (you can only focus on one), then do that in the isValid routine as well.
function isValid(f) {
var errorMessage = "";
var errorFields = "";
var isFocused = false;
...
if (field has an error) {
errorFields += " " + field.name;
if (!isFocused) {
field.focus();
isFocused = true;
}
}
...
if (errorFields.length > 0) {
errorMessage = "Errors in fields: " + errorFields;
}
return (errorMessage);
}
then, in your calling routine:
var errorMessage = isValid(f);
if (flag == 0 || errorMessage.length == 0) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert(errorMessage);
return false;
}
return true;

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.
Here's the phone number with dashes form that is working:
//Validates phone number with dashes.
function isTwelveAndDashes(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
and this is the one I can't manage to work out.
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') {
pass = false;
}
}
if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
You can do it very easily with regex:
return !!phone.match(/\(\d{3}\)\d{7}/g)
Live DEMO
Update:
The code you had didn't work because you forgot the else if:
else if (i == 4) { // Added the "else" on the left.
Checking phone number with RegEx is certainly the way to go. Here is the validation
function that ignores spaces, parentheses and dashes:
check_phone(num) {
return num.replace(/[\s\-\(\)]/g,'').match(/^\+?\d{6,10}$/) != null}
You can vary the number of digits to accept with the range in the second regular expression {6,10}. Leading + is allowed.
Something like that (a RegExp rule) can make sure it matches either rule.
var numbers = ['(1234567890','(123)4567890','123-456-7890','1234567890','12345678901'];
var rule = /^(\(\d{3}\)\d{7}|\d{3}-\d{3}-\d{4}|\d{10})$/;
for (var i = 0; i < numbers.length; i++) {
var passed = rule.test(numbers[i].replace(/\s/g,''));
console.log(numbers[i] + '\t-->\t' + (passed ? 'passed' : 'failed'));
}
EDIT:
function isDigit(num) {
return !isNaN(parseInt(num))
}
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') return false;
} else if (i == 4) {
if (c != ')') return false;
} else if (!isDigit(c)) return false;
}
return true;
}
// or...
function isTwelveAndPara(phone) {
if (phone.length != 12 || phone.charAt(0) != '(' || phone.charAt(4) != ')') return false;
for (var i = 1; i < phone.length, i != 4; i++) {
if (!isDigit(phone.charAt(i))) return false;
}
return true;
}

Comparing numbers wrong

I have the following JS which compares credit card number length:
validate: function () {
var ccLength = $('.credit-card input[name="cc_number"]').val().length;
var cardType = parseInt($('.credit-card .credit-card-type .selected').attr('rel'));
if (!isNaN(cardType)) {
console.log(ccLength); //11
console.log(provider[cardType].validLength.split(',')); // ["16", "13"]
if (ccLength == 0 || (cardType > 0 && (ccLength < parseInt(provider[cardType].validLength)) || (!$.inArray(ccLength, provider[cardType].validLength.split(','))))) {
triggerNotification('x', 'Your credit card number isn\'t long enough');
return false;
} else {
if ($('.credit-card input[name="cc_cvv"]').val().length < 3) {
triggerNotification('x', 'You must provide a CCV');
return false;
}
}
} else {
triggerNotification('x', 'Credit card type is not recognized or accepted');
return false;
}
return true;
},
I've included the values of console.log() on the 5th & 6th lines. For some reason, it doesn't fail...
update
provider[cardType].validLength is always either '16,13' or '16'
$.inArray( 16, ['16'] ); //=>-1

Categories

Resources