check a textbox for invalid characters using js and regular expressions - javascript

I am having a hard time figuring out how RegExp work.
I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:
<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">
Now, what I do is create an input textbox which will run a js function whenever its content is changing.
<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else {
// Regex stuff goes in here
}
}
Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?

If you want the regex to check for invalid characters in the field, you can use this.
^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.

You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:
ValidationExpression="^[^#%&*:<>?/{|}]+$"
EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:
new RegExp(validationExpressionGoesHere);

[^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else if(val.match(/[^#%&*:<>?/{|}]+/)) {
// Valid
}
else {
// Invalid
}
}

Related

javascript : problem with regular expression

I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat
You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3
RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"
This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);

How to Validate textbox so that I cannot enter zero as first digit?

How should I validate my textbox so that I the text entered shouldnt start with zero. I can enter zero anywhere else in the textbox...
function checkFirst() {
var text = document.getElementById('<%=textbox.ClientID %>').value.charAt(0);
if (text == "0") {
return false;
}
}
I tried with this code but it shows JavaScript Runtime error is thrown. I dont know how to clear it.
If there are any choices in regular expressions too pls suggest me some.
Use JQuery and JavaScript match function to check textbox value by using regular expression:
function checkFirst() {
var text = $('#<%=textbox.ClientID %>');
return text.val().match("^[1-9][0-9]*$") != null; //wil work only if you allow only numbers in your input, otherwise replace the regex.
}
You'll have to do the same check on server although. There you use asp:RegularExpressionValidator with same validation expression as on client side.
Use this regular expression to validate the textbox value -
^[a-zA-Z1-9][a-zA-Z0-9.,$;]+$
This will not allow 0 as the first character.

Validation on onKeyUp

I need to do validation onkeyup and onsubmit.
I have field called CVV which accepts 3 or 4 digits numbers, so i'm using '^(d){3,4}$'.
This pattern works properly when i did in onsubmit function, but in onkeyup function i get always false even i enter 3 digits number.
<input type="text" onkeyup="callonkeyup(this,'First Name','^(d){3,4}$')" value="First Name">
function callonkeyup(tag,defaultValue,pattern){
var isValidate = validate(pattern,trim(tag.value),defaultValue);
console.log("==isValidate=="+isValidate+"==tag.value=="+tag.value+"===pattern==="+pattern);
}
function validate(pattern,value,defaultVal){
var returnValue = false;
if(value && value != defaultVal){
while(pattern.indexOf('\\\\') != -1) {
pattern = pattern.replace('\\\\', "\\");
}
var testPattern = new RegExp(pattern,"");
if (testPattern.test(value)){
returnValue = true;
}else{
returnValue = false;
}
}
return returnValue;
}
function trim(value){
return value.toString().replace(/^\s+|\s+$/g,'');
}
Working DEMO
You need to escape back slash (\) so your regular expression should be ^\\d{3,4}$ instead ^(d){3,4}$
You need to add a \ in front of the d, without it the d is represented as the character d and not a numeric value. Here's the expression you should use ^\d{3,4}$.
EDIT
The first part was on track, but I missed that you were passing the pattern as a string to another function. If you were to run new RegExp('^\d{3,4}$', "") it would work, but because it was being passed through a function, the \ character was being removed. In order to pass a string with a backslash in it, you need to escape the slash with another back slash like so \\. This means your new expression should be ^\\d{3,4}$.
When developing regular expression I usually use something like http://regexpal.com/ to help test them. Keep in mind that for this one you would have to check the ^$ match at line breaks (m) box for it to match multiple tests on multiple lines

jQuery regexp validation

I would like to validate user input client side with a little jQuery function that is called onsubmit on my form. I want the field #fname (first name) to only allow a-z, A-Z and space. The return false is supposed to be stopping the form from submitting.
function validateregister(){
if (!($("fname") =~ [a-zA-Z ])) {
return false;
}
}
This is my HTML:
<input type="submit" value="Join now!" id="registersubmit" class="paddingoutline2" onsubmit="return validateregister()">
Of course, i'm going to validate the user input on the server side later on. When I submit the form, it gives me an "internal server error". This makes me think that I made an error in my function validateregister(). Is there anything wrong? If the I'm pretty new to jQuery so any help is appreciated.
Thanks!
What you want is
function validateregister(){
return /^[a-zA-Z ]+$/.test($('#fname').val());
}
Apart fixing the selector suggesting the use of the val and test functions, I took the liberty to change the regex :
^ and $ force the test to cover the whole string
the + requires at least one character
But are you aware that this regex might be too strict if you want people to type their real first name ? Yours, for example, would not pass...
You have to use regex this way:
function validateregister(){
var nameRgx = /[a-zA-Z]/;
var phoneRgx = /[0-9]/;
if (!nameRgx.test($("#fname").val())) {
return false;
}
if (!phoneRgx.test($("#phone").val())) {
return false;
}
}
And make sure to refer your elements with Either with # id notation or . class notation. In your code you are not referencing your elem in a proper way.
^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression;
also forces minimal matching when an expression might
match several strings within a search string.
More Info about Regex writing

Regex to match carriage return in Javascript

I am trying to write some Javascript to hide some elements that contain only carriage returns. I appreciate that the correct way to solve this problem would be to stop these elements being created, but unfortunately that is not possible in this instance. I am trying to user a regular expression to search for the unwanted elements but am not having much luck. The function I have written is as follows:
function HideEmptyP()
{
var patt = (\\r)
for(var i = 0;i<desc[i].length;i++);
{
var desc[i] = document.getElementsByClassName('sitspagedesc');
var result[i] = patt.test(desc[i]);
if (result[i] == true)
{
desc[i].style.display='none';
}
else
{
alert("No Match!");
}
}
The error I'm getting in the Web Console is 'Syntax Error: Illegal Character'.
Grateful for any ideas on how to solve this.
Thanks in advance.
I am trying to write some Javascript to hide some elements that contain only carriage returns.
There's no need for a regular expression for that, just compare the element's innerHTML property to "\\r", e.g.:
if (demo[i].innerHTML === "\\r") {
// Remove it
}
But beware that some browsers may transform a single carriage return. You might want to check for "\\r", "\\n", and just a space. To do that, you might want to use a regular expression.
Your regular expression literal ((\\r)) is just completely invalid, it's worth reading up on them to learn the correct syntax. To write a regular expression literal in JavaScript, you use / as the delimiter. So: /\\r/. To test that a string contains only \r, \n, or space, you can use /^[\r\n ]+$/ (which requires there be at least one character that matches, and uses ^ to indicate start-of-string, and $ to indicate end-of-string):
if (demo[i].innerHTML.match(/^[\r\n ]+$/) {
// Remove it
}
The reason you are getting Syntax error is because the declaration
var patt = (\r)
is incorrect it should be somethign like var patt = '\r';
Also the whole for loop is wrong.
You should define demo before you start the for loop not inside it, and result need not be an array but just a normal variable
Your litteral seems odd.
Try var patt = /\r/;
var patt=/\n/gi
should work.
extra i flag to denote case insensitive.
g for global search.

Categories