jQuery regexp validation - javascript

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

Related

Use Whitelist RegEx in Javascript to validate a string

I'm trying to prevent an action based on wether a string passes the whiteList Regex in Javascript
const whiteList = /[#A-Za-z0-9.,-]/g // Regex from external source. It will be difficult to modify.
const str= 'ds%d';
console.log(str.replace(whiteList, '').length === 0) // Expected false - WORKS
// How can I make this statement return false ?
console.log(whiteList.test(str)) //Expected false Actual true
Tried using replace command to check if a string passed a validation based on a whitelist. It works but I believe there could be a better way of solving this problem.
You get true from test because there is a character in the string that matches the expression. The expression has no anchors, so it's not that it requires all characters in the string to match, just one. To require all characters to match, you'd need a "start of input" assertion (^) at the beginning, an "end of input" assertion ($) at the end, and either a "zero or more" (*) or "one or more" (+) quantifier on the character class (depending on whether an empty string should pass).
If you're getting the expression from elsewhere, you can add those to it after the fact:
const whiteList = /[#A-Za-z0-9.,-]/g // Regex from external source. It will be difficult to modify.
const str= 'ds%d';
console.log(str.replace(whiteList, '').length === 0);
const improvedList = new RegExp("^" + whiteList.source + "+$");
console.log(improvedList.test(str)); // Now shows false
That does make the assumption that the original regex has the problem described. You might check first, but it would be easy to construct regular expressions that seemed like they needed modifying but didn't.
Alternatively, just use the replace check you have, since it works as well. It's not that much more expensive.

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: Check input string is not only upperccase and is not only lowercase

What is the regex to check if input string is NOT lowercase only, it is NOT uppercase only and does NOT contain numbers.
Validation must fail
SIMO TEST
SIMO344
simo
simo3432
These are ok
SIMO test
Simo
Welcome to Stackoverflow
When posting a question, please make sure to include your attempts, so that we can help guide you to an answer. This website is not meant to give you the answer, but to help guide you to an answer, or to explain your error. It's more rewarding to help you if we are simply guiding you and not giving you the answer. You'll probably get more response too. Please remember that when posting next time.
I tried to explain regular expressions in JavaScript, and tried to guide you through the logic in my answer.
Your case
You can use the .test function of a RegExp to test if a string matches a regular expression. You can then invert that result to check if the string does not contain it. Each of the cases you mentioned is a separate expression, which can be joined by the | operator.
Testing if a string is lowercase only:
In a RegExp, a - can be used to indicate a range of characters. There are already specially assigned codes for commonly used ranges, such as \s for a white space. The + operator means one or more. The ^ means starts at the beginning of the line(string) and $ means starting the end.
^[a-z\s]+$
Testing if a string is uppercase only:
This is the exact same as the lowercase case, but the character range is for uppercase letters:
^[A-Z\s]+$
Testing for digits
The regex code \d is short for a range of digits (you can essentially think of it as [0-9], but it also accounts for unicode).
\d
Putting it all together
^[a-z\s]+$|^[A-Z\s]+$|\d
And in a condition, it would be:
if (!/^[a-z\s]+$|^[A-Z\s]+$|\d/.test(your_string_here)) {
// the string isn't uppercase only, lowercase only
// and doesn't contain a digit
}
Please see the below code snippet. Modify as per your requirement.
function validate(strInput) {
var re = /\d/;
if(re.exec(strInput)===null){
re = /^(?!.*[a-z\d]).+$/;
if(re.exec(strInput)===null){
re = /^[A-Z][a-z]*/;
if(re.exec(strInput)!==null)
return re.exec(strInput);
}
}
return false;
};
console.log(validate("SIMO TEST"));
console.log(validate("SIMO344"));
console.log(validate("Simo"));
console.log(validate("simo"));
console.log(validate("simo3432"));
console.log(validate("SIMO2 TEST"));
console.log(validate("Simo3"));
console.log(validate("SIMO test"));
function CheckPassword() {
var inputtxt = $('#text12').val();
console.log(inputtxt)
var passw = /(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
var passWN = /\d/;
if (inputtxt.match(passw)) {
if (!inputtxt.match(passWN)) {
alert('Correct, try another...')
return true;
} else {
alert('Wrong...!')
return false;
}
} else {
alert('Wrong...!')
return false;
}
}

check a textbox for invalid characters using js and regular expressions

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
}
}

How can I customize this javascript function?

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.

Categories