JS Regex Pattern Used In Data-XXX Attributes Not Working - javascript

i am trying to set regex pattern in input field attribute and use js to validate it.. but somehow it's not working..
if i use same pattern directly on js it works.. but not through the attribute..
here is my html code:
<input type="text" name="tPhoneNumber" id="tPhoneNumber" style="width:90%;" data-name="Phone Number" data-group="NewEntry" data-required="y" data-pattern="/^\+44[\d]{10}$/" />
and here is the js code:
//this works
if (/^\+44[\d]{10}$/.test(inputs[i].value))
{
console.log("matched");
}
else
{
console.log("not matched");
}
//this does not works, it's always failed regardless whether the text box has correct value or not
if(!inputs[i].value.match(inputs[i].dataset.pattern))
{
var msg = `Invalid data entered in "${inputs[i].dataset.name}" field!<br/>You have entered = ${inputs[i].value}`;
return ShowError(msg);
}
what i am doing wrong here?
thanks in advance
best regards

Since data attribute inside your input is just string, not a RegExp object, you should remove slashes / at start and end of its value: data-pattern="^\+44[\d]{10}$"
var input = document.getElementById('tPhoneNumber');
//this works
if (/^\+44[\d]{10}$/.test(input.value))
{
console.log("matched");
}
else
{
console.log("not matched");
}
//this should works too
if(!input.value.match(input.dataset.pattern))
{
console.log(`Invalid data entered in "${input.dataset.name}" field!<br/>You have entered = ${input.value}`);
}
<input type="text" name="tPhoneNumber" id="tPhoneNumber" value="+440123456" style="width:90%;" data-name="Phone Number" data-group="NewEntry" data-required="y" data-pattern="^\+44[\d]{10}$" />

Your in-code regex works because you are using a regular expression literal, which creates an instance of RegExp. A regular expression literal is a regular expression placed between forward-slashes (optionally followed by flags).
Your attribute pattern does not work because custom data attributes are represented as strings in JavaScript.
So when you call .match(dataset.pattern), you pass a string instead of a RegExp object. The string converts to a RegExp object.
The leading and trailing forward-slashes are JS syntax for creating a RegExp object, so data-pattern and your JS RegExp are not the same.
data-pattern should only represent the regular expression, so that it will be converted correctly; remove the forward-slashes of data-pattern.

Related

validation illegal characters going through with valid

Why does my javascript form validation allow illegal characters through when valid characters are entered alongside them?
Here is my script
//Address Validation
var Address1 = document.forms ["tiptopform"]["Address1"].value;
var message="Please enter a valid Address" ;
var problem=false;
var patt1=new RegExp (/[A-Za-z0-9-]/);
var result = patt1.test(Address1);
if (result){
message=message;
problem=true
}
if (problem) {
alert (message)
}
I have tried reversing the true and false variable but that as expected only reverses the problem.
You are testing if you regular expression can be found within prvided address.
You want to match whoel adress and tets if it conatins only specific characters, use:
/^[A-Za-z0-9-]*$/
that is from start to end any number of those characters
sidenote: /regexp/ is a waz to write dont regular expression, zou don't have to call new RegExp or you can provide this regualr expression as string then use
new RegExp ("^[A-Za-z0-9-]*$");

Convert string to regex using regexp and test values in javascript

I have a regular expression that is in string form, I want to bind that regex to my grid cell. Such that, now the values in that cell are validated against that regex. I am using RegExp JavaScript library for conversion and testing the value. But it is either returning false everytime or giving me an invalid regex, even for the simplest of the regex used.
This is the method I am using:
addCellValidator(columnObj[0].name, new CellValidator({
isValid: function (value) {
var regex = new RegExp("/^[a-zA-Z\-]+$/");
return value == "" || (regex.test(value));
}
}));
Is it the format or any special pattern required by the RegExp?
While this is valid JavaScript code:
new RegExp("/^[a-zA-Z\-]+$/")
... it doesn't generate the regular expression you think. It's equivalent to this:
/\/^[a-zA-Z-]+$\//
You'll have to:
Strip delimiters
Extract and parse flags, if any, e.g.:
"/^[a-z-]+$/i" ---> new RegExp("^[a-z-]+$", "i")
One more note: there's no point in escaping - with backslash. If want to match a literal - inside a character class you need to put it as first or last item.
You just added the / / to the string, this works:
addCellValidator(columnObj[0].name, new CellValidator({
isValid: function (value) {
var regex = new RegExp("^[a-zA-Z\-]+$");
return value == "" || (regex.test(value)); }
}));

Why this JavaScript RegExp results in dual answer?

Look at this simple HTML input tag:
<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex'
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />
<p id='log'></p>
Now imagine that we want to validate this field, using this function:
var log = $('#log');
function validateRegex(field) {
var pattern = field.attr('data-validation-regex-pattern');
log.append(pattern + '<br />');
if (pattern && pattern != '') {
var isValid = new RegExp(pattern).test(field.val().trim());
if (!isValid) {
log.append('not valid<br />');
}
else {
log.text('valid<br />');
}
}
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());
Now, if you look at the log, you see that this line returns false:
var isValid = new RegExp(pattern).test(field.val().trim());
However, this line of code returns true:
new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());
In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.
Why? What's wrong here?
To see it in action, look at this fiddle.
Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:
data-validation-regex-pattern='^\+\d{2}\.\d{10}$'
Will work just fine:
Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/
\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.
Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).
To get your code work, replace double slashes (\\) in your HTML by a single slash.Fiddle: http://jsfiddle.net/GRL2m/5/
Extra information:
In HTML, HTML entities (eg ") are used to display special characters.
In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.

Extracting strings from an input field using regular expressions and jQuery

I am trying to match a string in an input field using a regular expression /[1-9][a-zA-Z]/ and insert it into a <p> tag using jQuery.
I modified this example from the jQuery API docs to include the following if statement. When I type '1A' in the input field it works, however I want to exclude the rest of the string so that the <p> only includes the matched string portion.
$("input").keyup(function () {
if($(this).val().match(/[1-9][a-zA-Z]/)){
var value = $(this).val();
};
$("p").text(value);
}).keyup();
Did I explain that clearly? Could anyone point me in the right direction?
Much appreciated,
So what you are doing in the above code is that if the value of the input field matches the regular expression, you assign its value to <p> tag. Since, you want to assign the matched string to the <p> tag, you should do:
$("input").keyup(function () {
var match = $(this).val().match(/[1-9][a-zA-Z]/);
if(match){
var value = match[0]; // Your problem was here
};
$("p").text(value);
}).keyup();
The match method of a String returns an array containing the match if it passed or undefined if the match failed.

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