Form Validation With Regex - javascript

I've written a function to validate if a password is valid. The only problem I'm having is figuring out why this pattern that I've written in JavaScript isn't evaluating to true when tested with a password such as: 'SteveRogers#256'. Is this an issue with the way I've declared the regex pattern?
PHP
function check_password($pass_word)
{
$pattern = "#.*^(?=.{8,15})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W).*$#";
return (preg_match($pattern, $pass_word));
}
JavaScript
function check_password(pass_word) {
var pattern = new RegExp("#.*^(?=.{8,15})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W).*$#");
return pattern.test(pass_word);
}

Remove regex delimiters in Javascript as new RegExp takes a String in the constructor. Correct Javascript code should be:
var pattern = new RegExp("^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?\\W).{8,15}$");

Related

Nodejs regexp validation for sip URI string

var uriRegExp = /^(sip):\(?([0-9]{3})\)?[- ]?([0-9]{3})[- ]?([0-9]{4})#\w+(\ w+)*(\.\w)(\.\w{2,3})+$/;
Is this a correct regular expression for validating the string
sip:1-999-123-4567#voip-provider.example.net ?
No, this regex does not match your string.
If you want to know why you could have a look at https://regex101.com/r/EC0xFN/1 .
There you can interactively build and check your regex with different input strings.
Here is a simple sip URI validator, that i have created, using regular expression.
function myFunction() {
var str = "sip:+91989556926#test.est.test.com";
var regExp = /^(sip):(\S+[0-9])#\S+(\w+([.-]?\w+)*).(\w{2,3})$/;
var result = regExp.test(str);
document.getElementById("demo").innerHTML = result;
}
Please check the link.
[https://regex101.com/r/5vMfI9/4][1]

ng-pattern Vs script validation

I'm validating date (Format is YYYY/MM/DD) using regular expression ng-pattern. When i use below code in UI, it's working fine.
<input type="text" class="k-fill" ng-pattern="/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/" ng-model="Request.ExpDate" id="ExceptedDate" name="ExceptedDate" ng-readonly="true" required />
But i want to validate the pattern inside of a function for pop-up a validation message. For achieving it I used below code inside one of my js file.
var str = Request.ExpDate;
var x = '/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/';
var patt = new RegExp(x);
var res = patt.test(str);
if res return false, I can show a message. But the problem is, it is returning false for every dates which are even in the right format.
May I know the reason for why the regexp is working fine with ng-pattern and why it is not working properly inside JS function?
Your regex returns false all the time because you included regex delimiters in the pattern that you initialize with a constructor notation (new RegExp(var)).
You do not have to use a constructor and can initialize RegExp using a regular literal in the form of /.../:
var str = Request.ExpDate;
var patt = /((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/;
var res = patt.test(str);
However, it seems your regex has some issues in it, here is a fixed version:
/^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/
I removed {1} limiting quantifier since it is redundant, and removed , from inside the character classes [1,2] and [0,1] since the comma was treated as a literal, and could mess up the results. We can also further enhance by removing unnecessary groups or turning them to non-capturing, but those are already cosmetic changes.
See sample:
var str = "2992/10/31";
var patt = /^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/;
var res = patt.test(str);
document.write(res);
Note that you could also make use of Date.Parse to validate the date more precisely.

RegEx conversion to use with Javascript

I'm currently using this RegEx ^(0[1-9]|1[0-2])/(19|2[0-1])\d{2}$ in .NET to validate a field with Month and Year (12/2000).
I'm changing all my RegEx validations to JavaScript and I'm facing an issue with this one because of /in the middle which I'm having problems escaping.
So based on other answers in SO I tried:
RegExp.quote = function (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
var reDOB = '^(0[1-9]|1[0-2])/(19|2[0-1])\d{2}$'
var re = new RegExp(RegExp.quote(reDOB));
if (!re.test(args.Value)) {
args.IsValid = false;
return;
}
However, validations fails even with valid data.
Remove ^ of first and $ from end of regex pattern. And add \ before any character which you want to match by pattern. so pattern is like this:
(0[1-9]|1[0-2])\/(19|2[0-1])\d{2}
You can test your regex from here

Regular Expression to validate email: illegal character

Doing form validation using Jquery without plugins, they're easy enough to use. Trying to teach myself regular expressions and at a wall.
var email = $('#email').val();
// Validate email address
// Regular expression to match email address:
var emailReg = \S+#\S+;
if(email.match(emailReg)) {
// Pass
}
else {
// Fail
$('#email').css("background","yellow");
var counter2 = setTimeout("$('#email').css('background','white')", 3000);
return false;
}
I know it's the worlds simplest regular expression, just trying to get functionality and I'll get more sophisticated later.
Keep getting SyntaxError: illegal character \S (here) +#S+
Don't understand why. Have searched this site and tried dozens always with console errors.
Add / around it.
var emailReg = /\S+#\S+/;
^ ^
You need to place your regex in forwardslashes like so:
var emailReg = /\S+#\S+/;
This way it knows it's a regex object, instead of just random operators put together
You could also do:
var emailReg = new RegExp("\S+#\S+");
This method is useful if you aren't just writing a static regex (eg. getting the regex from user input)
Regular expressions are enclosed in forward slashes in js. Try
var emailReg = /\S+#\S+/;

regular expression not working when provided in double quotes in javascript

I am trying to use regular expession in javascript but it is not working. My custom control contains property called RegEx which is provided by user and I need to validate the input value against this regex. As properties in JS will be in double quotes("") the regualr expression fails(case -1). Case 2 succeeds thought both the cases regualr expression is same, the only difference is case- 1 it goes as double quotes. can somebody tell me why it is not working.
RegexExp="/^\d{5}$/"- at my aspx page
var value = "11111";
if(value.toString().search($(element).attr('RegexExp')) != -1)
{
return true;
}
else
{
return false;
}
var reg = /^\d{5}$/;
if(value.toString().search(reg) != -1)
{
return true;
}
else
{
return false;
}
Do this instead:
var reg = new RegExp($(element).attr('RegexExp'));
Update: you also need to strip the / characters, as these shouldn't be given to the RegExp constructor:
var regexExp = $(element).attr('RegexExp');
var reg = new RegExp(regexExp.substring(1, regexExp.length - 1));
I assume that the code that you posted is part of the function from the return statements, but if it is not, your first problem is that return is not allowed to be used out side of functions.
In any case, try the following. You can create a RegExp from a string by using its formal constructor
value.search(new RegExp($(element).attr('RegexExp')));
Also, you do not need to use toString() on value since it is already a string and your code is unnecessarily verbose. The following is equivalent to your first if else statement
return value.search(new RegExp($(element).attr('RegexExp'))) != -1;
Edit:
If you want to be able to pass in an expression as "/[expression]/" or "/[expression]/gi", you can do the following:
var toRegExp = function(regexString) {
var expression = regexString.substr(1), // remove first '/'
closingSlash = expression.lastIndexOf("/"); // find last '/'
return new RegExp(
// Expression: remove everything after last '/'
expression.substr(0, closingSlash),
// Flags: get everything after the last '/'
expression.substr(closingSlash+1)
);
}
....
value.search( toRegExp($(element).attr('RegexExp')) );
First, don't use a custom attribute to hold a regular expression. Second, "RegexExp" is redundant — that's like saying "regular expression expression". Third, to convert from a String to a RegExp, you have to wrap the string with new RegExp(); JavaScript is not weakly typed. That said, assuming that the regular expression isn't being set server-side, I'd recommend using jQuery's data API. It has the added advantage that it can store regular expression objects directly.
To set:
jQuery.data($(element).get(0), "regexp", /^\d{5}$/);
To get:
jQuery.data($(element).get(0), "regexp");
But ultimately, what you really want is the jQuery Validation plugin. It does everything you need and then some. Incidentally, it uses the data API internally to work its magic.
Documentation
The /.../ syntax is used to declare a regular expression object in Javascript, so you shouldn't use that to specify a regular expression pattern, it should be just regexp="^\d{5}$" as the attribute.
The search method takes a regular expression object as parameter, so you have to create a regular expression object from the string that you get from the attribute:
var reg = new RegExp($(element).attr('regexp'));
if (value.toString().search(reg) != -1) {
(You see the similarity with your second case?)
Or as a single expression:
if (value.toString().search(new RegExp($(element).attr('regexp'))) != -1) {

Categories

Resources