Pattern validation with JavaScript - javascript

I want a pattern with letters and numbers only.
This is how I do it...
JavaScript file:
var pattern_checked = checkPattern();
function checkPattern(){
var elem = document.getElementById("name");
var pattern = elem.getAttribute("[a-zA-Z0-9_]");
var re = new RegExp(pattern);
if (re.test(elem.value)) {
return true;
} else {
return false;
}
}
But in both the cases, I'm getting false.
What is wrong in this code?

I believe you meant to do:
function checkPattern() {
var elem = document.getElementById("name");
// Allow A-Z, a-z, 0-9 and underscore. Min 1 char.
var re = /^[a-zA-Z0-9_]+$/;
return re.test(elem.value);
}

Example fiddle
Your problem should be at this line.
var pattern = elem.getAttribute("[a-zA-Z0-9_]");
Attribute should usually have a name with value. But from your example, it seems like the value is also name.
The HTML code should be something like below:-
<input type='text' id='name' pattern='[a-zA-Z0-9_]'>
Then to get the pattern
var pattern = elem.getAttribute("pattern");

Related

create regexp for username validation

I need some help creating regexp. It's just I don't quite understand how to create a regexp. How do i create a validation for username with some rules like this
only Uppercase, lowercase, underscore(_) and dot(.) are allowed
start with an underscore(_)
I've already tried some regexp from mozilla developer site, but it doesn't seems right
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username.value);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
I expect some username like so
_username = true
_username1 = false
.username = false
username = false
and also are there any sites for me to understand how to create regexp, because I got some more thing to do with it
function validuser(username) {
var msg = "valid";
var usernameRegex = new RegExp(/_+[A-Za-z]/);
var usernameRegexFound = usernameRegex.test(username);
if (!usernameRegexFound) {
msg = "Invalid Username";
}
return msg;
}
console.log(validuser("_username","Valid?"));
console.log(validuser("_username1","Invalid?"));
console.log(validuser(".username","Invalid?"));
console.log(validuser("username","Invalid?"));
When creating regex, you can help yourself using https://regex101.com/.
That said, here is your regex :
function test(username) {
const regex = new RegExp('^_{1}[A-Za-z\.]*$', 'i');
// Alternative version considering #thomas points
// const regex = new RegExp('^_[A-Za-z._]+$', 'i');
return regex.test(username);
}
console.log(test('test'));
console.log(test('_test'));
console.log(test('_te.s.t'));
console.log(test('_teST'));
console.log(test('Test_'));
console.log(test('^zdq^dz.'));
console.log(test('_teS/T'));
console.log(test('_9901A'));

Manipulate input string while doing a regex search

trying to find every match in a string and process it with a custom function and replace it in the string. When I set text = to the new string though, it never changes, and in the end remains the unchanged.
function submit () {
var searchTerm = document.querySelector('#search-term').value;
var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\d', 'g');
var match, matches = [];
//search for replacements
while ((match = regex.exec(text)) != null) {
var beforeMatch = output.substring(0, match.index);
var afterMatch = output.substring(match.index + match[0].length, text.length);
text = beforeMatch + replaceFunction(match[0]) + afterMatch;
console.log(text);
}
console.log('result', text);
}
function replaceFunction (input) {
return input * 2;
}
You can achieve same result with far less code using replace() and its function's callback that takes match as parameter.
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
text = text.replace(/\d+/g, function(match){
return parseInt(match) * 2;
})
console.log(text)
First of all, you need to use \\ for escape sequence if you are using RegExp constructor. Alternatively you can use the RegExp literal as shown below. Moreover you are using only \d which is going to match a single digit. Instead you should be using \d+ that will match the complete number.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
When using the constructor function, the normal string escape rules
(preceding special characters with \ when included in a string) are
necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');
Then you are trying to manipulate the string using a loop. Instead simply use replace function as shown below.
function submit () {
// var searchTerm = document.querySelector('#search-term').value;
// var replaceFunction = Function('input', document.querySelector('#function').value);
var text = '<part id="cursor_crosshair" x="96" y="32" w="16" h="16" focusx="7" focusy="7" />';
var output = text;
var regex = new RegExp('\\d+', 'g'); // <<<<<< RegExp constructor
// OR
regex = /\d+/g; // <<<<<<< RegExp literal
var match, matches = [];
console.log(text);
output = text.replace(regex, replaceFunction);
console.log('result', output);
}
function replaceFunction (input) {
return parseInt(input) * 2;
}
submit();
Disclaimer: Using RegExp for manipulating HTML elements and attributes is not a good idea and you may end up in unexpected issues if its not used carefully. Use it at your own risk.

Using Java Script or jquery regex to verify if a string contains another string

I am building a simple search where query string can have wild cards '*'. Search terms can be like following:
animal
ani*
*mal
an*al
all above should return true if the word is 'animal'.
how this can be done in JS / jquery?
will appreciate for help.
rnv
The match on a string is simple:
var mystring = "This is my string";
var myregex = /*some regex*/
var results = mystring.match(myregex); // you can also write the regex directly as the argument of the match method, without using any variable.
So in your case you could have:
var mystring = "animal";
var myregex = new RegExp(inputQuery.replace(/\*/g, '.*'), 'gi'); // gi stands for 'global' and 'ignorecase' when applying the regex
var results = mystring.match(myregex);
Beware that .* matches zero or more (comes from the * whildcard) character, ANY character (comes from the .)
If you want to match zero or more letter, number or underscoreuse \w*, if you want to match one or more, use \w+, and if you want to match a specific number of letters, use \w{x} (\w{3} matches exactly 3 letters).
var str = "anim*";
var replaced = str.replace("*", ".*");
var regex = new RegExp(replaced);
var result = regex.test("animal");
console.log(result);
change the str variable to get the result as true or false;
Implemented version - https://jsfiddle.net/dpoqnacv/1/
var regexString = '^'+ $('#searchbox').val().replace("*",".*") + '$';
if(new RegExp(regexString).test('animal'))
$('#resultdiv').html('Matching...');
else
$('#resultdiv').html('Not Matching...');
You can just transform your wildcard into a RegExp and perform your search. Here is a simple example.
var search = document.getElementById("search");
var result = document.getElementById("result");
result.style.color = "red";
function fsearch() {
var str=search.value;
str = str.replace("*", ".*") //Transform your wildcard into a RegExp
result.innerHTML = "animal".match(new RegExp(str));
}
<label for="search">Search : <input name="search" id="search" type="text"/></label>
<input id="ok" type="button" value="ok" onclick="fsearch()"/>
Result : <div id="result"></div>
not bad answers but i think its easier with .test();
var str = "my dog is an animal";
/dog*anim*/.test(str); //returns true
/d*mal/.test(str); //returns true
etc
give it a try

convert regex string to regex object in javascript

I am getting regex string from json object (yes its dynamic and will be always be string) i want to test this with textbox value.
But even if i pass valid input text it does not pass regex condition
code :
var pattern = "/^[A-Za-z\s]+$/";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
Fiddle :- http://jsfiddle.net/wn9scv3m/
Two problems:
You need to escape the backslash.
You need to remove the forward slashes on the beginning and end of string.
Corrected code:
var pattern = "^[A-Za-z\\s]+$";
var str = "Some Name";
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}
http://jsfiddle.net/wn9scv3m/3/
Use regex-parser:
const parseRegex = require("regex-parser")
parseRegex("/^hi$/g")
// => /^hi$/g
This should work for you (jsfiddle: http://jsfiddle.net/wn9scv3m/9/):
var pattern = /^[(\w)|(\s)]+$/; // using / regex constructor...
var altPattern = "^[(\w)|(\s)]+$"; // using quotes and new RegEx() syntax...
var regex = new RegExp(altPattern);
var str = "Some Name";
if (str.match(pattern) != null && regex.test(str) != null) { // check using both methods
alert('valid');
}
else {
alert('invalid');
}
As far as I can see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions you are combining two methods to declare RegExp. If you are using the string variant, then don't include the "/" character before and after the expression, example:
var pattern = "^[A-Za-z\s]+$";
pattern = new RegExp(pattern);
If you like the /regexp/ form better, then use it without quotes:
pattern = /^[A-Za-z\s]+$/;
this should work
var str1 = "SomeName"; //true
var str2 = "SomeName123"; //false
function MyRegex(val) {
var pattern = /^[A-Za-z\s]+$/;
var match = pattern.exec(val);
return match !== null && match[0] === val;
}
alert(MyRegex(str1));
alert(MyRegex(str2));

Javascript pattern for test from input value

What I want is simple. I have an input field and I want to check what items from an unordered list (ul) contain the input's value.
So, I have this:
$('input#search').keyup(
function() {
var value = $(this).val();
if (value.length > 0) {
var patt = /value/g;
console.log(patt);
$('ul#list li').filter(function() {
return (patt.test($(this).html()));
});
}
}
);
My problem here is that if, for example, the value of the input is 'abcd' patt will be /value/g instead of /abcd/g so I want to know how can I insert the value in the pattern.
To create a pattern based on dynamic data you'd use the RegExp ctor passing it a string of the pattern. e.g.
var word = 'foo';
var re = new RegExp(word, 'g'); // var re = /foo/g
Don't forget to escape characters with special meaning in regexp.
However, if you're just looking for a simple "is x within y" comparison, indexOf can perform this check very quickly:
var sample = 'this is a foo sentence';
var loc = 'Hello, world!'.indexOf('world') // 7
then simply check if indexOf(...) != -1.
define patt as new RegExp
var patt = new RegExp(value,"g")

Categories