KnockoutJS validation - Model variable regex not behaving as expected - javascript

I have a knockout model build for a form and am using knockout for validation also. One particular field is giving me issues. The requirement for the textbox is it should allow any number of numerics [0-9], and optionally, up to 2 decimal places. My variable looks as follows
var debtIncomeRatio = ko.observable().extend({
required: {
onlyIf: function () {
return (isQualified() == "Qualified" && (!nonReportable() && !isFinanced()));
},
message: "* Required"
},
pattern: {
message: '* Number, no more than 2 decimal places',
params: '^[0-9]+(\.[0-9]{1,2})?'
}
});
My regex expression above, ^[0-9]+(\.[0-9]{1,2})?, should work from every forum and thread I have read. I have also tested it on sites like https://regex101.com/, which verifies that it should work. But in reality, when entering data on my form, it is allowing things such as 33,33, 33!33
or any special character in place of a decimal. Have I got a piece incorrect somewhere? Or does anybody know why it is it behaving this way?

Try using a regex literal instead of a string.
pattern: {
message: '* Number, no more than 2 decimal places',
params: /^[0-9]+(\.[0-9]{1,2})?/
}

I'm not sure why, but I couldnt not get a regex literal to work either, but I found my error when using a regex string. Referring to this answer I found on S.O. Knockout-Validation Using Regular Expression to Validate a Phone Number, when using a regex string you must escape your backslashes, which I didn't know.

Related

how to correctly use Yup/formik number validation ReactJs

I would like to explain my problem of the day.
I'm using a simple number type validation
number: Yup.number()
.required("Required")
.max(100000000, "To big")
.min(0, "Not negative number")
my problem is ,in the entry of the field, I can add only one letter the "e", I do not understand why
example "12e3"
while I would like to enter only numbers
example "123"
if you have any ideas, thank you
Neff
There is more than one way to achieve your only number input.
The problem is not yup.
check your input before sending. Exclude using ASCII
check your input before sending. Exclude using Regex1 or Regex2
change your input form type to number from basic html
You can't handle it with Yup. because "e" interprets as number. in math "e" is a way to represent scientific notation. You can use react-number-format for handling this.
Use this condition, it's take care of "e".
const digitsOnly = (value) => /^\d+$/.test(value)
Yup.object().shape({
mobile: Yup.string().required('please_enter_mobile').test('Digits only', 'digits_only', digitsOnly).min(7,'please_enter_valid_mobile').max(15, 'Maximum number limits')
}).required()

Regex expression for exactly known pattern without "cutting into" the string not working

I am currently developing a web-application where I work with java, javascript, html, jquery, etc. and at some point I need to check that whether an input matches a known pattern and only proceed if it is true.
The pattern should be [at least one but max 3 numbers between 0-9]/[exactly 4 numbers between 0-9], so the only acceptable variations should be like
1/2014 or 23/2015 or 123/2016.
and nothing else, and I CANNOT accept something like 1234/3012 or anything else, and this is my problem right here, it accepts everything in which it can find the above pattern, so like from 12345/6789 it accepts and saves 345/6789.
I am a total newbie with regex, so I checked out http://regexr.com and this is the code I have in my javascript:
$.validator.addMethod("hatarozat", function(value, element) {
return (this.optional(element) || /[0-9]{1,3}(?:\/)[0-9]{4}/i.test(value));
}, "Hibás határozat szám!");
So this is my regex: /[0-9]{1,3}(?:\/)[0-9]{4}/i
which I built up using the above website. What could be the problem, or how can I achived what I described? I tried /^[0-9]{1,3}(?:\/)[0-9]{4}$/ibut this doesn't seem to work, please anyone help me, I have everything else done and am getting pretty stressed over something looking so simple yet I cannot solve it. Thank you!
Your last regex with the anchors (^ and $) is a correct regex. What prevents your code from working is this.optional(element) ||. Since this is a static thing, and is probably true, so it does not show any error (as || is an OR condition, if the first is true, the whole returns true, the regex is not checked at all).
So, use
return /^[0-9]{1,3}\/[0-9]{4}$/.test(value);
Note you do not need the (?:...) with \/ as the grouping does not do anything important here and is just redundant. The anchors are important, since you want the whole string to match the pattern (and ^ anchors the regex at the start of the string and $ does that at the end of the string.)
You need use the the following special characters in your regex expression:
^ and $
or \b
so 2 regexp will be correct:
/\b[0-9]{1,3}(?:\/)[0-9]{4}\b/i;
or
/^[0-9]{1,3}(?:\/)[0-9]{4}$/i

How to validate algebra expression in javascript

I'm new to Regular expression validations in JavaScript.
My textbox allows the user to enter a formula which needs to be validated client side.
The formula can be made of following operators:
+
_
*
/
(
)
%
These are the only symbols allowed in my textbox.
I need to validate the formula, which should have a form like CurrentbaseSalary+CurrentMBP(BPI). Something like +BPI-CBI( should not be considered valid.
You can use this regexp :
/^(\([+*%\/\-\d\s]+\)|[+*%\/\-\d\s]+)+$/.test('YOUR STRING')
this regexp check if you are using your allowed symbols and if parenthesis matches, but it cant check if "CurrentbaseSalary" is positive or negative, "CurrentMBP(BPI)" neither.
Some code, or more detailed example could help to find a solution.

How can I fix old javascript to validate an international phone number with jQuery Validate?

I found a blog post which shows a method of creating validation for an international phone number. The code supplied is:
jQuery.validator.addMethod('intlphone', function(value) { return (value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); }, 'Please enter a valid phone number');
I believe it used to work for me but something has changed - possibly a newer version of jQuery - and I'm getting this error:
Uncaught SyntaxError: Invalid regular expression: /^((+)?[1-9]{1,2})?([-s.])?(((d{1,4}))|d{1,4})(([-s.])?[0-9]{1,12}){1,2}(s*(ext|x)s*.?:?s*([0-9]+))?$/: Nothing to repeat
I created a JSBin with the items i'm working with, but I'm not having any luck getting rid of the error.
How can I fix old javascript to validate an international phone number with jQuery Validate?
ps: I believe I've tried running this with previous versions of jQuery and I'm still getting the error. I'm not sure what changed.
Ended up using this:
jQuery.validator.addMethod('intlphone', function(value) { return (value.match(/^((\+)?[1-9]{1,2})?([\-\s\.])?((\(\d{1,4}\))|\d{1,4})(([\-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); }, 'Please enter a valid phone number');
As stated here A comprehensive regex for phone number validation
It will be a lot easier to strip the non-digit characters and create a regex to match only the numbers and extension.
Add this to the beginning of your function to remove all non-digits other than x:
value.replace("[^\d+x]", "").match ....

Validate numbers, parenthesis and spaces only in jQuery validation

I am trying and failing hard in validating a phone number within jQuery validation. All I want is to allow a number like (01660) 888999. Looking around the net I find a million examples but nothing seems to work. Here is my current effort
$.validator.addMethod("phonenumber", function(value) {
var re = new RegExp("/[\d\s()+-]/g");
return re.test(value);
//return value.match("/[\d\s]*$");
}, "Please enter a valid phone number");
Bergi is correct that the way you are constructing the regular expression is wrong.
Another problem is that you are missing anchors and a +:
var re = /^[\d\s()+-]+$/;
Note though that a regular expression based solution will still allow some inputs that aren't valid phone numbers. You can improve your regular expression in many ways, for example you might want to require that there are at least x digits, for example.
There are many rules for what phone numbers are valid and invalid. It is unlikely you could encode all those rules into a regular expression in a maintainable way, so you could try one of these approaches:
Find a library that is able to validate phone numbers (but possibly not regular expression based).
If you need a regular expression, aim for something that is a close approximation to the rules, but doesn't attempt to handle all the special cases. I would suggest trying to write an expression that accepts all valid phone numbers, but doesn't necessarily reject all invalid phone numbers.
You may also want to consider writing test cases for your solution. The tests will also double as a form of documentation of which inputs you wish to accept and reject.
You need to use either a regex literal or a string literal in the RegExp constructor:
var re = /[\d\s()+-]/g;
// or
var re = new RegExp("[\\d\\s()+-]", "g");
See also Creating a Regular Expression.
Apart from that, you would need to use start- and end-of-string anchors to make sure that the regex matches the whole string, not only a part of it, and some repetition modifier to allow more than one character:
var re = /^[\d\s()+-]+$/g;
Another approach may be:
function(value) {
return /^\d+$/.test(value.replace(/[()\s+-]/g,''));
}
and if you want to check for the length of the number too, say it has to be a string with 10 digits:
function(value) {
return /^\d{10}$/.test(value.replace(/[()\s+-]/g,''));
}

Categories