Check pattern in javascript - javascript

I Have next pattern:
[a-z[A-Z]а-я[А-Я][0-9]їЇіІєЄ[-][,]_"/\ ]{0,483}
<input
id="<?= $field['id'];?>"
name="input"
<?php if (isset($field['regex'])) echo "pattern=".$field['regex'];?>
>
By this pattern I check data in field by javascript:
var decode_pattern = $(this).attr('pattern');
var reg = RegExp("^" + decode_pattern + "$");
But when i try to input (sdfzsdf) in field, regexp tell me - wrong.
Why?

I Have this pattern: [a-z[A-Z]а-я[А-Я][0-9]їЇіІєЄ[-][,]_"/\ ]{0,483}
JavaScript Regex syntax does't allow character classes in character classes. Maybe you meant
[a-zA-Zа-яА-Я0-9їЇіІєЄ,_"/\\ -]{0,483}
Your current regex is equivalent to /[a-z\[A-Z]а-я[А-Я]\dїЇіІєЄ-,_"\/ \]{0,483}/.
Also, since it contains a quote you will need to html-escape your attribute value:
echo 'pattern="'.htmlspecialchars($field['regex']).'"';

Related

How to remove characters when input not matches regex in JS

<input id="myInput" onblur="myFunction()">
<script>
function myFunction() {
var value= document.getElementById('myInput').value;
var regexCharacter = /[0-9|,]+/g;
strFirst = value.replace(regexCharacter, '')
document.getElementById('myInput').value = strFirst
}
</script>
I want to replace '' when the input does not match the regex's.
My regex just allow input number and comma.
My function is replace when input matching, i want to replace when it's not matching.
E.g a12,b2a => 12,2
can anyone help me, thanks.
Use /[^0-9|,]+/g as your regex. The ^ mark is used to match any character that's not in range.
Pro tip: You dont have to memorize all these tokens, just use a tool like https://regex101.com/
First of all, your function is not called to check the value with reqex.
then yout reqex replace "" when is number not charactors
<input type="text" id="myInput">
<script>
myInput.addEventListener("input", function (e) {
var value= document.getElementById('myInput').value;
strFirst = value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')
document.getElementById('myInput').value = strFirst
});
</script>
in this code you can write number whith dot
whith this reqex
value.replace(/[^0-9.]/g, '').replace(/(..?)../g
I think you should edit your regex to match letters instead of numbers. Like this: /[a-zA-Z|]+/g

Need to search arabic text in my web page

I have the following code which works fine for english but not working for arabic. how can i use this code for arabic also. how can I serach it as a string
function highlightSearch() {
var text = document.getElementById("query").value;
var query = new RegExp("(\\b" + text + "\\b)", "gim");
var e = document.getElementById("nav-5-3-primary-ver").innerHTML;
var enew = e.replace(/(<h6>|<\/h6>)/igm, "");
document.getElementById("nav-5-3-primary-ver").innerHTML = enew;
var newe = enew.replace(query, "<h6>$1</h6>");
document.getElementById("nav-5-3-primary-ver").innerHTML = newe;
}
#nav-5-3-primary-ver h6{
background-color:#FF9;
color:#555;
}
<input name="query" id="query" type="text" size="30" maxlength="30">
<input name="searchit" type="button" value="Search" onClick="highlightSearch()">
<div id="nav-5-3-primary-ver">
hello i am this
</br>
اذا كان الجهاز خارج التغطية هل يتم تسجيل البيانات للسيارة؟
</div>
There's a gotcha with \b (in javascript at least) : the notion of "word" it uses (to detect word boundaries) is :
sequences of characters in the set [a-zA-Z0-9_] (latin alphanumerics, plus the _ char)
It won't work as you expect for other charsets (note : even latin diacritics - letters with accents or signs on them - don't work).
Choose some other way to chek that you matched a complete word :
as suggested in this answer : you can write a predicate that matches "a space character or ^ or $"
or match the word without boundaries, and for each match, inspect the characters prior and next to that match
Links to ECMAscript specifications :
Assertions in Regular Expressions
Word Character definition

Regex check always return null\false\-1

I have a simple calculator on ASP.NET MVC5, front side is on HTML\CSS\Javascript.
In event handlers for buttons I concatenate all values into a string and want to check if it satisfies the regex. But, for example, if I put following values into my calculator: '99*66-', the code below returns null every time.
Here regex works okay: https://regex101.com/r/AxMvPe/1
Whole code: https://jsfiddle.net/0g79hkbc/
var regEx = /[+-]?([0-9]*[,])?[0-9]+[-+\/*][0-9]*[,]?[0-9]+[-+\/*]/; //in case if problems will appear https://regex101.com/
$('.button').on('click', function () {
var buttonText = this.innerHTML;
var inputedText = inputElement.innerHTML + buttonText;
console.log(inputedText.match(regEx));
});
I have tried following options, but they didn't help:
to replace regex expression on Regex object
to use .test() instead of .match() (got false)
to use .search() instead of .match() (got -1)
I also tried to manually entered '99*66-' and then compare inputedText with javascript string '99*66-', it also returns false. Why?
Looks good to me, except that it will not match when there is for example 99*. You will need a repeating set of regex like: https://regex101.com/r/AxMvPe/2
Added floats to it :)
var regEx = /[+-]?([0-9]*[,])?[0-9]+[-+\/*][0-9]*[,]?[0-9]+[-+\/*]/; //in case if problems will appear
inputElement = $('#input');
$('.button').on('click', function () {
var buttonText = $(this).val();
var inputedText = inputElement.val() + buttonText;
console.log(inputedText.match(regEx));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='input' type='text' value='99*66' />
<input class='button' type='button' value='-'/>

jQuery each to find label for attr not working

I am getting an error and think i know why but not sure how to resolve it.... for example my for label / id is:
shipping_address[country] << i think because of the brackets []
and my JS is
$(document).ready(function() {
$("form :input").each(function(index, elem) {
var eId = $(elem).attr("id");
var label = null;
if (eId && (label = $(elem).parents("form").find("label[for="+eId+"]")).length == 1) {
$(elem).attr("placeholder", $(label).html());
$(label).remove();
}
});
});
Error:
js__jquery.js?1419646…:1468 Uncaught Error: Syntax error, unrecognized
expression: label[for=billing_address[first_name]]
Example HTML:
<div class="col-sm-6">
<div class="form-group">
<label for="card[first_name]">First Name<span> * </span></label>
<input id="card[first_name]" name="card[first_name]" type="text" class="form-control" value="" validate="true">
</div>
</div>
Wrap the attribute value within quotes or escape metacharacter since the id value contains some metacharacter which has special meaning in jQuery.
.find("label[for='" + eId + "']")
// -^-----------^-
From jQuery docs :
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
FYI : Use text() method instead of html() method to get text content.
$(elem).attr("placeholder", $(label).text());
// ------^^^^^^---
Square brackets inside attribute selectors need to be escaped.
var eId = elem.id.replace(/[\[\]]/g, '\\$&');

Javascript strip after X characters prior to form submit

UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?
Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));
Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).

Categories