Javascript feedforward validation - javascript

I'm facing a problem where I would like to give an user an immediate feedback that an input field already doesn't comply following a validation pattern and not after providing the whole value.
To give you an example:
UK postcode might look like this [SW1W 0NY] and I would like to inform the user that everything looks good so far when he enters [SW] but give him immediate feedback when he enters for example [1].
How would you approach this? Since UK postcode can be up to 7 numbers I don't want to create 7 regular expressions to check the postcode against based on the postcode length but rather have some 'feedforward' machanism.

The final validation could look like this:
/^[a-zA-Z]{1,2}[0-9]{1,2}[a-zA-Z]{0,1} ?[0-9][a-zA-Z]{2}$/
And for the partial validation I would try something like this:
^([a-zA-Z]{1,2}([0-9]{1,2}([a-zA-Z]{0,1}( ?([0-9]([a-zA-Z]{1,2})?)?)?)?)?)?$
all the parts are optional, just make sure, that even in the last part can be one or two chars.

Related

Regular Expression to validate if user has provided the correct URI format or not

I am trying to write a regular expression or regex for my HTML input field with text type. The user should enter the URI in the input field. The URI would look something like this: urn:URNNamespace:**:class:ObjClassid.
Some of the examples of valid URI are as follows:
urn:abc:testing:pqrs:1234556.1244
urn:wxyz:testing123:abc:1234556.*
urn:global:standard:value:myvalue
I was trying to check only if the initial characters are URN using the expression ^(urn):// and check if the string contains the character : in it.
I just want to make sure that user enters valid URN similar to the one that's provided. Is there any better way I can use and achieve this?
I would recommend a really great tool called Regulex that helps you build regular expressions.
I tried to create the described pattern and ended up with:
^urn:\w+:\w+:\w+:\d+(\.\d+)?$
You can try and change it here

Check if string contains calculation

The question is as simple as the title: How do I make sure a string contains a calculation.
I have a string which should contain a calculation. The string could be something like this: "10 * 10 / 2 * 3". But there are always people who want to break things, so I want to check if it's a calculation. The user could fill in something like this: "alert('hi!')".
When I use eval(), it will still alert the user (if the user filled in: "alert()").
Does anyone know how I can check if the string contains a calculation and nothing else?
If you just want to check if a string contains an arithmetic operation, you coul match it with a regexp like this:
([-+]?[0-9]*\.?[0-9]+[\/\+\-\*])+([-+]?[0-9]*\.?[0-9]+)
BUT, i strongly suggest to use a javascript library as mathjs, or the JavaScript Expression Evaluator library, with which you can do, for example:
Parser.evaluate("3 ^ x", { x: 7 });
These libraries will take care to ignore code injection, for sure... :-)
In this case, I'd recommend a different solution.
Rather than trying to white list your string to ensure it is just math expressions, I'd recommend you try to use library specifically for handling math in the first place.
I have no experience with it, but a quick google of "javascript math parsers" brought me to this one: http://mathjs.org/docs/expressions/parsing.html
You could just check the input sting for characters. If the sting contains any characters like (a,b,c ... z) then you do not eval it.

How to write JavaScript form validation regex

I'm really new to HTML and JavaScript and I'm working on using regex to validate input...
I used /^[a-z]+$/i.test (firstName) to make sure the entered first name was all characters.
if( /^\d{8}$/.test(idNum)) doesn't seem to be working. I'm trying to make sure they enter an 8 digit number.
I've got to validate some other fields like Address, city, state, zip and phone number. Any resources or examples would be great!
Thanks!

Regex validation quick fix most likely

I am try to validate a form to make the user enter their full name like the following..
First, Last
The user must have some string of alphabetic only chars, then a comma, then a space, then a last name, which can again be any string of chars.
This is my current regex..
var alphaExp = /^[a-zA-Z,+ a-zA-Z]+$/;
However, it lets the user submit something as simple as john. I want it to force them to submit something such as john, smith.
What you are doing is creating a character class ([]) that matches any of the following characters: a-zA-Z,+. This allows john to match the whole regex.
This is what you want:
/^[a-zA-Z]+, [a-zA-Z]+$/
However, I would like to advise you that making assumptions about names is a little wrong. What if some guy is named John O'Connor? Or Esteban Pérez? Or just Ng (only a first name)?
"Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong" - tchrist
Sure, you don't want to let people to enter just gibberish, but leave an option for users to enter something that doesn't necessarily fit your idea of correctness, but is nonetheless correct.
That's not how character sets work:
/^[a-zA-Z]+, [a-zA-Z]+$/
Things to consider:
Any validation you do on the client can be bypassed
Some people may have names with accented letters
Some cultures don't use just two names
^[a-zA-Z]+, [a-zA-Z]+$
Should work, however, do you want to prevent '.'? As in J. Hooker? And more words, like 'Jan van Hoogstrum'? Note also that you are preventing any accented characters being used. An option (although it allows underscores) is to use \w:
^(\w+ )$
Which would give you 'name name name...'. 'First, last' is not a common way to enter your name, so you'll frustrate a lot of users that way.
The correct regexp for allowing only the first letter to be capital would be:
/^[A-Z][a-z]+, [A-Z][a-z]+$/

regular expression with if statements

I have this as my regular expression:
var email = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
And this is my if statement:
if($('#email').val() ==""){
$('#emailErrorMsg').text("Please enter a valid email address.");
}
else if(!email.test('#email')) {
$('#emailErrorMsg').text("OK");
}
else($('#emailErrorMsg').text("Please enter a valid email address."));
});
When I type in a valid email address it says "OK". However, if I enter just some text for example it still says "OK" when I want it to say "Please enter a valid email address". Anyone any idea. By the way, I'm still an amatuer at this stuff!
The main problem is that you have a ? at the end of the regex, following parentheses that enclose the entire pattern. This effectively makes the entire match optional, so the regex will literally match anything.
Note also that you are testing the literal string #email, not the value of the #email element. Make sure you pass the appropriate string to test().
I see that you have jquery tag, so take a look to JQuery validate plugin, it will be better than a simple regex.
But if you still want regex, see Validate email address in JavaScript?
Validating emails is hard. The fully correct regex is a true monstrosity that you can see (if you dare) at http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html which probably isn't what you want.
Instead, you have a few options. Use a regex that matches 99% of emails, do it server side with an email validation library, or implement a finite state machine to parse it correctly. The state machine is probably too bulky (although allows neat stuff like suggestions for possible typos) and doing it all server side -- which you better be doing anyway (what if someone has JavaScript disabled?) -- loses the benefits of as-you-type checking.
That leaves a simpler regex that doesn't match all legal emails, but matches enough that the chances of someone registering with one that it doesn't are really slim.
The regex from Validate email address in JavaScript? should do the trick pretty well:
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\
".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
Also, you made a small typo:
else if(!email.test('#email')) {
$('#emailErrorMsg').text("OK");
}
is testing against the string '#email' -- not the element with the ID 'email'. Change that to:
else if(!email.test($('#email').val())) {
$('#emailErrorMsg').text("OK");
}
There's a little typo in your regex. Try this:
var email = /^([\w-\.]+)#([\w-]+\.)+[\w-]{2,6}?$/;
That should also handle the .museum case

Categories