Comparing numbers wrong - javascript

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

Related

Javascript if statement, adding string into guarantee number checker

Currently I have this if statement which checks through numbers when registering a guarantee number in a gravity form, however I now need to check through the numbers with a mandatory string that a customer needs to enter immediately before the number as currently they're able to enter just the number and it will search though the guarantee registered numbers whether they have a string in front of them or not...
So for example = searching PO983278 or PT983279 instead of just checking 983278 or 983279.
**Below is a snippet of the current if statement which works great when just checking a number.
**
$productName = $_POST['productName'];
$guaranteeNumber = preg_replace('/[^0-9 ]/','',$_POST['guaranteeNumber']);
if($productName === 'Product One') {
if((300000 <= $guaranteeNumber) && ($guaranteeNumber <= 430000)) {
$confirmation = guaranteeDbCheck($guaranteeNumber);
} else {
$confirmation = 'Invalid Number';
}
} elseif($productName === 'Product TWO') {
if((261000<= $guaranteeNumber) && ($guaranteeNumber <= 411000)) {
$confirmation = guaranteeDbCheck($guaranteeNumber);
} else {
$confirmation = 'Invalid Number';
}
}
echo $confirmation;
**So I'd like to be able to do something like...
**
if($productName === 'Product One') {
if(('PO' + 300000 <= $guaranteeNumber) && ($guaranteeNumber <= 'PO' + 430000))
**But of course this doesn't work, any advice on if anyone has done something similar would be great!
**
Thanks!
$productName = $_POST['productName'];
$guaranteeOriginal = $_POST['guaranteeNumber'];
$guaranteeNumber = preg_replace('/[^0-9 ]/','',$_POST['guaranteeNumber']);
if($productName === 'Product One') {
if((300000 <= $guaranteeNumber) && ($guaranteeNumber <= 430000)) {
$confirmation = guaranteeDbCheck($guaranteeOriginal);
} else {
$confirmation = 'Invalid Number';
}
} elseif($productName === 'Product TWO') {
if((261000<= $guaranteeNumber) && ($guaranteeNumber <= 411000)) {
$confirmation = guaranteeDbCheck($guaranteeOriginal);
} else {
$confirmation = 'Invalid Number';
}
}

Multiple condition for phone number field in javascript

I have below code:
$('.mobileNumber').keyup(function () {
var mobile = $(this).val();
var numericExpression = /^[0-9]+$/;
if (mobile.length == 0 || mobile.length < 10 || !mobile.match(numericExpression)) {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','block');
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
}
});
what i'm trying to do is whenever my mobileNumber fields blank(ie. o length),less than 10 length and it should follow numbers only. if yes, then error message i.e. .jp-error-msg-kstm will appear else not.
for example, if i entered 1234567890 then it should not show me the error whereas if erase the value and make the field as 0 length or less than 10 then it should shoe the error span div.
Simply use .length.
if (mobile.length < 10 || !mobile.match(numericExpression)) {
I have used
mobile.length == 0
in the first if condition only.
So the code become
$('.mobileNumber').keyup(function () {
var mobile = $(this).val();
var numericExpression = /^[0-9]+$/;
if (mobile.length < 10 || !mobile.match(numericExpression)) {
if(mobile.length == 0){
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','block');
}
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
}
});

What is the best way to validate reactive form field in Angular2?

I am trying to validate Reactive form field in Angular 2. Here i have written custom validator, I am not sure whether this is right approach to do validation. But any how i am not getting accurate result through my code, some of the test cases are failed. If any one knows please correct me the code as well as approach, if it is wrong.
These are my conditions,
Text field should be 4 to 14 alphanumeric if wildcards are entered. Otherwise it is 7 to 25 alphanumeric.
a. If asterisk (*) is entered, that must be the last character and should be 5 to 13 alphanumerics.
b. If question mark (?) is entered, it can be in any position between5 and 14 inclusive. It would be accepted for the following text length.
i. 7
ii.10
iii.11
iv. 13
v. 14
c. If wildcards are not entered, it can be 7 to 25 alphanumeric s.
This is my code, which i have written custom validator.
static ProductTypeValidation(min: number, max: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null =>{
if(c && (c.value !== '')){
const s=c.value;
var reg=/[^A-Za-z0-9]+/;
var reg1=/[^A-Za-z0-9*?]+/;
if(!s.match(reg)){
if(s.length<7 || s.length>25){
console.log('Invalid with size')
return{
'ProductTypeValidation': true
};
}
else{
console.log('valid with size');
return null;
}
}else{
if(s.match(reg1)){
console.log('Main Error');
return{
'ProductTypeValidation': true
};
}else{
for(let i=0;i<s.length && i<4;i++){
if(s.charAt(i).match(reg)){
console.log('Invalid first');
return{
'ProductTypeValidation': true
};
}else{
console.log('valid');
return null;
}
}
if(s.length>4 && s.length < 14 ){
for(let i=4;i<13;i++){
if(s.charAt(i) == '*'){
if(s.charAt(i+1) == ''){
console.log('valid');
return null;
}else{
console.log('Invalid *');
return{
'ProductTypeValidation': true
};
}
}
}
}
if(s.length>4 && s.length <15){
for(let i=4;i<14;i++){
if(s.charAt(i) == '?'){
if(s.length == 7 || s.length == 10|| s.length == 11 || s.length == 13 || s.length ==14){
console.log('valid');
return null;
}
else{
console.log('Invalid?');
return{
'ProductTypeValidation': true
};
}
}
}
}
for(let i=13;i<s.length && i<25;i++){
if(s.charAt(i).match(reg)){
console.log('Invalid remaining');
return{
'ProductTypeValidation': true
};
}else{
console.log('valid');
return null;
}
}
}
}
}
return null;
};
}
You should call custom validator in your Form controller, then your form controller will take care to call your method each key press.
'productType': new FormControl('', [CustomValidators.productTypeValidation(6,25)]);
I finished writing 'custom validator' for the aforementioned circumstances, but when I call it from the project, it is only valid for the first key press, even though it is a function that gives me the correct result when testing differently.Can any one please correct me.
Here is my updated code.
//Custom validator for Product type
static ProductTypeValidation(min: number, max: number): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null =>{
if(c && (c.value !== '')){
const s=c.value;
var reg=/[^A-Za-z0-9]+/;
var reg1=/[^A-Za-z0-9*?]+/;
var reg2=/[^A-Za-z0-9*]+/;
var reg3=/[^A-Za-z0-9?]+/;
if(s.match(reg))
{
if(s.match(reg1))
{
console.log('Apart from special char existed')
return{
'ProductTypeValidation': true
};
}else{
if(s.length < 4)
{
console.log('special char existed but length is minimum');
return{
'ProductTypeValidation': true
};
}else{
if(s.charAt(0).match(reg) || s.charAt(1).match(reg) || s.charAt(2).match(reg) || s.charAt(3).match(reg))
{
console.log('first 4 positions it self special char existed');
return{
'ProductTypeValidation': true
};
}else{
if(s.length>4 && s.length<=14)
{
if(s.match(reg2) && s.match(reg3))
{
let a=s.indexOf('*');
let b=s.indexOf('?');
if(b>a)
{
console.log('Invalid after * everything is invalid');
return{
'ProductTypeValidation': true
};
}else if((s.charAt(a+1) == '') && (s.length == 7 ||s.length == 10 || s.length == 11 ||s.length == 13 || s.length == 14) && (a<13))
{
console.log('valid with all conditions * and ?');
return null;
}else{
console.log('Invalid ? and *');
return{
'ProductTypeValidation': true
};
}
}
else if(s.match(reg2))
{
if(s.length == 7 || s.length ==10 || s.length == 11 || s.length == 13 || s.length == 14)
{
console.log('valid with ?');
return null;
}else{
console.log('invalid with ?');
return{
'ProductTypeValidation': true
};
}
}else{
let a=s.indexOf('*');
let b=s.indexOf('?');
if(s.length>4 && s.length <14)
{
if(b>a)
{
console.log('Invalid after * everything is invalid');
return{
'ProductTypeValidation': true
};
}else if(s.charAt(a+1) == '')
{
console.log('vaid with *');
return null;
}else{
console.log('Invalid with *');
return{
'ProductTypeValidation': true
};
}
}else{
console.log('* exceeded the size');
return{
'ProductTypeValidation': true
};
}
}
}else{
if(s.match(reg))
{
console.log('After 14 no special characters are allowed');
return{
'ProductTypeValidation': true
};
}else{
console.log('it will return null');
return null;
}
}
}
}
}
}else{
if(s.length<7 || s.length>25){
console.log('size not matched');
return{
'ProductTypeValidation': true
};
}else{
console.log('Size matched');
return null;
}
}
}
return null;
}
}

How does jQuery Validation setups the validation message?

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

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.

Categories

Resources