Validation Always Failing To Validate - javascript

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]+$/ );

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

Form validation regex and DOM: What would be the best way to implement regex in a form validation

Form validation regex and DOM:
What would be the best way to implement regex in a form validation?
Im currently doing this, but when I validate it's not matching the values:
if(this.value.length > 0 && this.value === /^[a-zA-Z]+$/ );
Thank You in advance!
you need to use the test() method.
var patt = /^[a-zA-Z]+$/; //define your RegEx
if(this.value.length > 0 && patt.test(this.value)){ //check if this.value is longer than one character AND matches your RegEx
//do something
};
See http://www.w3schools.com/jsref/jsref_regexp_test.asp
Why you code does not mathing any values?
Because you used typewise equality test ===. In dynamic types of JavaScript world it states for: test types of those values if they are the same and then test values if they are equal.
So when you were trying to test in that way values of some textboxes, which are strings
typeof('a')
this code will yield "string" because of 'a' is indeed a string. But:
typeof(/^[a-zA-Z]+$/)
this will yield "object". As you see typewise equality test will always return false when you are trying compare string to object.
That is for testing equality of objects and its values. For regex see 'bam' answer.

Detecting whether user input contains a forbidden character in 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/

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

Categories

Resources