How can I customize this javascript function? - javascript

I have this javascript function that block special characters...
function validaTexto(texto)
{
!(/^[A-zÑñ0-9]*$/i).test(texto.value) ? texto.value = texto.value.replace(/[^A-zÑñ0-9]/ig, '') : null;
}
The problem is that this function doesn't allow me to type blank spaces... how can I customize this function to allow me some other things, such as blank spaces, "," , "." , ";" and so on?
Thanks!!

change the regex to this:
!(/[^A-zÑñ0-9 ,\.;]*$/i)
also, the function is quite redundant in that it checks the string twice, basically saying "Does the string contain any of these characters? Yes? Ok, so search the string for these same characters and remove them. Just change it to this:
function validaTexto(texto) {
texto.value.replace(/[^a-zñ0-9 ,\.;]/ig, '');
}

function validaTexto(texto) {
texto.value.replace(/[^A-z0-9 ,\.;]/ig, '');
}
Referenes (with examples):
http://www.regular-expressions.info/
http://regexlib.com/

Read this post:
Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)
With a bit of effort, you should be able to modify your regex to do what you need.

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);

Regex return undefined in a JavaScript String

I have a little code snippet where I use Regular Expressions to rip off punctuation, numbers etc from a string. I am getting undefined along with output of my ripped string. Can someone explain whats happening? Thanks
var regex = /[^a-zA-z\s\.]|_/gi;
function ripPunct(str) {
if ( str.match(regex) ) {
str = str.replace(regex).replace(/\s+/g, "");
}
return str;
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));
You should pass a replacement pattern to the first replace method, and also use A-Z, not A-z, in the pattern. Also, there is no point to check for a match before replacing, just use replace directly. Also, it seems the second chained replace is redundant as the first one already removes whitespace (it contains \s). Besides, the |_ alternative is also redundant since the [^a-zA-Z\s.] already matches an underscore as it is not part of the symbols specified by this character class.
var regex = /[^a-zA-Z\s.]/gi;
function ripPunct(str) {
return str.replace(regex, "");
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));

Regular expression allowing only characters that will not break a link

Anybody can help me with regular expression which will only accept alphabetical letters from English alphabet and numbers without whitespaces ( ÖÜÕÖ and similar characters + whitespaces will break the HTML link this thing is creating )?
I currently have :
/[A-Za-z ]\S+$/
but this will allow whitespaces and ÖÜÄ and similar at the beggining.
function validatenumber(el) {
var regex = /[A-Za-z ]\S+$/;
if( !regex.test(el.value) ) {
alert('invalid value');
}else{
alert('correct value');
}
}
http://jsfiddle.net/qd7BL/1375/
Here's a fiddle.
Try
/^\w+$/
It'll allow only a non empty string, containing english alphabet letter, both cases, underscore and digits in a string.
/^[A-Za-z0-9]+$/
Solved the problem, although I should probably think is more through as much more elements are allowed in link.
Also, the best solution was to use Slugify, a plugin for jQuery which will make the input correct format.

Javascript Regexp validation not quite working

I am trying to use RegExp validation for a number that can have up to 5 numbers followed up one option decimal place. Like 48293 or 23.4 are good. 99.99 or 453543 are not. I wrote the following function:
function validateLoad(load_value) {
var matchValue = new RegExp('[0-9]{1,5}(\.[0-9]{1})?')
return matchValue.test(load_value)
}
However, this seems to return true for all numerical values, can anyone tell me how to fix this?
You need to use anchors to make sure the entire string (and not just a substring) is matched by the regex. Also, don't forget to double the backslashes if you construct the regex from a string (and drop the {1}, it's a no-op):
var matchValue = new RegExp('^[0-9]{1,5}(\\.[0-9])?$');
Using literal notation would avoid to escape backslashes :
function validateLoad(load_value) {
return /^\d{1,5}(\.\d)?$/.test(load_value)
}

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

Categories