validation illegal characters going through with valid - javascript

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-]*$");

Related

JS Regex Pattern Used In Data-XXX Attributes Not Working

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.

JS - Nothing to repeat In match function

The error is simple. In JS I try to do somtehing to similar a preg_match in PHP. I found match function. I use this function to compare a value with strings elements. If found something return true, else return false.
I tried this
var sim_action = $(this);
if(sim_action.data("phone").toString().match("/^(+34|0034|34)+([67]){8})$/")){
But return this error.
Invalid regular expression: //^(+34|0034|34)+([67]){8})$//: Nothing
to repeat
So the question is. How can i add this string in JS match function?
You need to escape the + characters with a backslash: /^(\+34|0034|34)\+([67]){8})$/. You also have a closing bracket which doesn't have a matching opening bracket.
+ and () are metacharacters and if you want to refer to the literal, you need to escape them with a \. Here's a regex101 demo which highlights the errors with your regex
As for the regex, from wikipedia, I gather that spanish phone numbers have the format +34(6|7)xxxxxxxx
You can use this regex: /^(\+34|0034|34)[67]\d{8}$/
If you just want to check if the regex passes , you can use regex.test(<stringToBeTested>)
const regex = /^(\+34|0034|34)[67]\d{8}$/
const phone = "+34712345673";
if (regex.test(phone))
console.log("Valid phone number")
const phoneNumbers = ["+34712345673", "0034612345673", "+34812345673"]
phoneNumbers.forEach(p => console.log(regex.test(p)))

Regex not working properly in Javascript code

I have a JavaScript function that fires successfully on the onkeypress/onkeyup event for an asp.net textbox control as follows:
<asp:TextBox ID="txtboxLatestTag" runat="server" onkeypress="validate()" onkeyup="validate()"></asp:TextBox>
function validate() {
var str = $("#txtboxLatestTag").val();
var pattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}/gm
if (!str.match(pattern))
{
document.getElementById("txtboxLatestTag").style.color = "red";
}
else
{
document.getElementById("txtboxLatestTag").style.color = "white";
}
The regex is supposed to match entries in the format of:
10.10.10.10 or
1.1.1.1
or anything allowing 1 to 2 digits between each "." character.
This works, however the problem is that it ALSO matches with
1.1.1.100 i.e. it should not allow 3 numbers at the end of the string, only 2.
This works perfectly in regexr.com but I cannot figure out why it is matching on this.
Thank you
I believe what you want to do to exclude extra characters at the end of the string is add in the end of input character $ (or end-of-line character, since you're using multiline mode). This will cause extra characters at the end to invalidate the match. For example:
var oldPattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}/gm;
console.log("Old pattern match:");
console.log("10.10.10.100".match(oldPattern));
var pattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}$/gm;
console.log("New pattern match:");
console.log("10.10.10.100".match(pattern));
console.log("10.10.10.1".match(pattern));

Regular expression failed in URL address test

I try to build an Regular expression to check valid URL address. for now I tested different address and all was good , but those next (valid) address's failed:
url = "http://example.com/tr/vvf/index.php/docs/po/trf"
//url = "http://example-a.mydomain.com/test/ny" also not working
var pattern = new RegExp("(https|ftp|http)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?");
pattern.test(url)
I think because of the index.php/doc... Any ideas how to fix it
Just use regex literal instead of RegExp object:
var pattern = /(https|ftp|http):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/;
RegExp works with a string, that requires you to do double escaping so \w becomes \\w in it.
See it working here

What's wrong with my JavaScript regex / regex syntax?

I need a regex to use with javascript/jquery that fits these rules...
it will include 10 digits
if there is a leading 1 or +1 it should be ignored
valid characters allowed in the field are... 0-9,(), and -
I found a regex at Snipplr (the first one), but its not working. First of all, I'm not even sure if that regex fits my rules. Secondly, its allowing inputs like &^%$$#%^adfafsd. I believe the error is in my code not the regex. For example, are there supposed to be quotes around the expression?
Here is the code that is supposed to be validating the phone field...
$('#phone').bind('blur', function() {
var pattern = new RegExp("^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$");
if(pattern.test($('#phone').val())){
$("#phone").addClass("error");
return false;
}else{
$("#phone").removeClass("error");
return true;
}
return true;
})
When you're not using the literal form ( /[regex]/ ), you need to escape the regex string. Try this instead:
var regex = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/;
if(regex.test($('#phone').val()){ ... }
if there is a leading 1 or +1 it should be ignored
it will include 10 digits
valid characters allowed in the field are... 0-9,(), and -
That could be matched with an expression like:
/^(?:\+?1)?[()-]*(?:\d[()-]*){10}$/

Categories

Resources