Detecting whether user input contains a forbidden character in JavaScript - javascript

I have a text box that is going to be validated in JavaScript upon click on the submit button.
Only the character 0-9 and a-f and A-F are allowed.
So g-z and G-Z as well as other characters such as punctuation or not allowed.
The code I have so far is:
function validate_form ( )
{
valid = true;
if ( document.form.input.value == [a-zA-Z_,.:\|] )
{
alert ( "You can only enter either 0-9 or A-F. Please try again." );
valid = false;
}
return valid;
}
Which doesn't seem to work.
I'm new to JavaScript so can any one please give me a hint as to where I'm going wrong?

We can actually clean this code up a lot. There's no need to keep track of valid as test() will provide us with the true or false value we're looking for. It's also a good deal easier in your case to keep a whitelist of acceptable characters rather than a blacklist. That is, we know every character we want, but can't possibly specify every character we don't want.
function validate_form() {
return /^[a-fA-F0-9]+$/.test(document.form.input.value);
}
Note that you can also use this to do a pre-check:
document.form.input.onkeyup = function() {
if (!validate_form()) {
alert("You can only enter either 0-9 or A-F. Please try again.");
}
};

the syntax is /^[a-zA-Z_,.:\|]+$/.test(document.form.input.value). Notice the ^ and $: without them, the test will pass even for strings that have only at least one allowed character.

The best way for validation is to not let the user, enter wrong character. Use this code (this is the jQuery version, but you can also convert it easily to JavaScript):
$('#inputFiledId').keyup(function(e){
// checking the e.keyCode here, if it's not acceptable, the return false (which prevents the character from being entered into the input box), otherwise do nothing here.
});
This is called pre-check. Please consider that you whatever you do in client-side, you should always check the values at the server also (have server-side validation) as there are multiple hacks around, like form-spoofing.

You could do something like this
$('input').keyup(function(){
var charac = /[g-zG-Z;:,.|_]/;
var result = charac.test($(this).val());
if(result == true){
alert('You can only enter either 0-9 or A-F. Please try again.');
}
})
http://jsfiddle.net/jasongennaro/GTQPv/1/

Related

Combine whitelist and blacklist in javascript regex expression

I am having problems constructing a regex that will allow the full range of UTF-8 characters with the exception of 2 characters: _ and ?
So the whitelist is: ^[\u0000-\uFFFF] and the blacklist is: ^[^_%]
I need to combine these into one expression.
I have tried the following code, but does not work the way I had hoped:
var input = "this%";
var patrn = /[^\u0000-\uFFFF&&[^_%]]/g;
if (input.match(patrn) == "" || input.match(patrn) == null) {
return true;
} else {
return false;
}
input: this%
actual output: true
desired output: false
If I understand correctly, one of these should be enough:
/^[^_%]*$/.test(str);
!/[_%]/.test(str);
Use negative lookahead:
(?!_blacklist_)_whitelist_
In this case:
^(?:(?![_%])[\u0000-\uFFFF])*$
Underscore is \u005F and percent is \u0025. You can simply alter the range to exclude these two characters:
^[\u0000-\u0024\u0026-\u005E\u0060-\uFFFF]
This will be just as fast as the original regex.
But I don't think that you are going to get the result you really want this way. JS can only go up to \uFFFF, anything past that will be two characters technically.
According to here, the following code returns false:
/^.$/.test('💩')
You need to have a different way to see if you have characters outside that range. This answer gives the following code:
String.prototype.getCodePointLength= function() {
return this.length-this.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g).length+1;
};
Simply put, if the number returned by that is not the same as the number returned by .length() you have a surrogate pair (and thus you should return false).
If your input passes that test, you can run it up against another regex to avoid all the characters between \u0000-\uFFFF that you want to avoid.

Javascript Validate domain dot com

im trying to make a javascript input validator.
I want to check the input if its in the correct domain format. It must check the specific input when the submit button is pressed.
If it is not the correct format, the form will not submit. I am not sure with my RegExp format. Also not sure with the whole code if it will run depending on how i wanted it to be.
Here's my code :
var x1=document.forms["leform"]["domain"].value;
validomain(x1);
function validomain(les) {
var tdomain = new RegExp('/[:alpha:]+/./[:alpha:]+/');
if(!tdomain.test(les)){
alert('not a valid domain format');
return false;
}
}
based on your comment:
examp.le any small letter(probably max 20 chars) dot any small latter
again (max 4 chars)
var x1=document.forms["leform"]["domain"].value;
validomain(x1);
function validomain(les) {
if ( !String(les).match(/^[a-z]{1,20}\.[a-z]{1,4}$/) ) {
alert('not a valid domain format');
return false;
}
}
Try
var tdomain = /^[\w-]+\.\w+$/;
\w are word characters.
The . is special (matches any character) and must be escaped.
Also, you might want to research what a valid domain can look like. (Want to match subdomains? what about domains with international characters?)
you can try this regex too:
function validomain(les) {
var pattern = new RegExp(/([a-z0-9-]+\.(?:com))(?:\/|$)/)
if(!pattern.test("les"))'{
alert('not a valid domain format');
return false;
}
}
#Crayon Violent is right may be you have a problem elsewhere in your code

Validation Always Failing To Validate

Tried to add in some validation to a form, but it keeps acting as if the data that is being validated is invalid, even if its valid!
if (document.getElementById("mileageNumber").value == /^[0-9]+$/)
{
if (document.getElementById("vehicleNumber").value == /^[0-9]+$/)
{
<Desired Action>
}
else
{
alert("Please Enter Numbers Only");
}
}
else
{
alert("Please Enter Numbers Only");
}
Can anybody see what i have done wrong?
You'll need to test the regex and not evaluate it as a value.
if(/^[0-9]+$/.test(document.getElementById("vehicleNumber").value)){
//Validation passed
}
You need to use the RegExp.test method.
/^[0-9]+$/.test(document.getElementById("mileageNumber").value);
You can also simplify your regular expression like so: /^\d+$/
You are comparing a string with a regex object. A regex object describes a structure of a regex object. A string is just a bunch of characters. They are simply not the same thing... ever. Just like the pseudo-code apples == carrots will never return true, string == regex will never return either. It requires a function to test if a string has the structure that the regex object describes.
You can properly test a string against a regex using string.match( .. ).
document.getElementById("vehicleNumber").value.match( /^[0-9]+$/ );

Form validation of numeric characters in JavaScript

I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.
<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
{
alert("University number (URN) field must be filled in");
cdp_form.univer_number.focus();
return false;
}
else if (is_valid = /^[0-9]+$/.test(x))
{
alert("University number (URN) field must have numeric characters");
cdp_form.univer_number.focus();
return false;
}
}
</script>
<input type ="text" id="univer_number" maxlength="7" size="25" name="univer_number" />
Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.
IsNumeric('1') => true;
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
You need invert your regular expression (add ^ inside [0-9]):
/^[^0-9]+$/
Your test condition is a bit strange:
else if (is_valid = /^[0-9]+$/.test(x))
Why have the redundant comparison to is_valid? Just do:
else if (/^[0-9]+$/.test(x))
Though the regex you are using will match numerals and only numerals - you need to change it to match anything that is not a numeral - like this /^[^0-9]+$/.
Better yet, get rid of the regex altogether and use IsNumeric:
else if (!IsNumeric(x))
On your line that says else if (is_valid = /^[0-9]+$/.test(x)), you're doing a simple assignment instead of testing that it is actually matching the regex.
Your pattern will still accept this input <b>##$##123 or ad!##12<b>. Use this pattern I created:
/[a-zA-Z-!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?]/
This pattern will check if it is alphabetic and special characters.
You need to test for the negation of the RegExp because you want the validation to alert upon failure, so just add ! in front of it:
else if (is_valid = !/^[0-9]+$/.test(x))
See example →
I know this is an old post but I thought I'd post what worked for me. I don't require the field to be filled at all but if it is it has to be numerical:
function validateForm()
{
var x=document.forms["myformName"]["myformField"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myformName.myformField.focus();
return false;
}
}

Disabling some special characters in text area

Hey guys, I'm thinking of ways to disable users from typing some special characters like < and >. But I would like them to use full stops and commas and question marks and exclamation marks and quotes. I've come up with this piece of code but it doesn't seem to allow any special character.:
<script type="text/JavaScript">
function valid(f) {
!(/^[A-zÑñ0-9]*$/i).test(f.value)?f.value = f.value.replace(/[^A-zÑñ0-9]/ig,''):null;
}
</script>
There are several ways of doing this, none of them are a good way to go tho, but we'll get to that.
you can bind to onkeyup/onkeydown/onkeypress events on the element and cancel events for characters you have blacklisted. This will not stop people from pasting the characters into the field however.
You can bind to the onchange event of the element and them remove the blacklisted characters from it, once the user is done inputting.
The problem with any type of sanitizing like this in javascript is that it is trivial for a user with a tiny bit of knowhow, to circumvent these measures and still upload the offending characters to the server anyway.
So if you don't want to allow special characters in the user generated input you should either
remove them serverside after the userinput has been submitted
keep them but encode them into html entities > and < for > and < for instance before outputting them anywhere on your webpage.
Try with this...
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.formname.fieldname.value.length; i++) {
if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
why not simply check the character pressed on "onKeyDown" event?
<textarea id="foo"></textarea>
<script>
document.getElementById('foo').onkeydown = validate;
function validate(){
var evtobj = window.event? event : e; // IE event or normal event
var unicode = evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey = String.fromCharCode(unicode);
]
return (/^[A-zÑñ0-9]*$/i).test(actualKey);
</script>
This simply gets the key which was pressed, and if it is a valid one returns true, otherwise false, this, in term, determines if the key is actually written in the textarea or not

Categories

Resources