Form validation of numeric characters in JavaScript - 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;
}
}

Related

javascript validation not working for only alphabetic values

I have used a javascript validation function to validate it. I've used it to see whether the text entered to the html textbox is alphabetic(No numeric characters allowed). The function is called during onkeyup and onblur. The only problem is even when numeric values or special characters are typed in the validation doesn't work. If I leave the field blank then it works(Displays that the field is left blank). Here's my javascript code:
function isAlphabetic(x,y){
var exp = /^[a-zA-Z]+$/;
var a = document.getElementById(y).value;
if(a=="" || a== null){
document.getElementById(x).innerHTML = "You cannot leave this feild empty";
return;
}
else if(a!="" && a!= null){
if(y.match(exp)){
document.getElementById(x).innerHTML = "";
return;
}
else{
document.getElementById(x).innerHTML = "Only enter alphabetic characters allowed";
return;
}
}
else{
return;
}
If you use y as an id of element, I suppose you shouldn't check it with your regexp. Instead you should check a:
if(a.match(exp)) {
You don't need JavaScript anymore for any of this. Use the pattern attribute on the input field and the browser won't let the user enter anything that doesn't match, and use required to prevent submitting the form with an empty value.
Also, do you really want only ASCII letters? (are spaces allowed? how about non-ASCII letters such as "é"?)

RegEx for fixed number of digits?

I'm finishing a form I have to do for my homework, and just when I thought I was finished, I found a mistake.
I need a RegEx for input field that would return an alert if there's not exactly 13 digits.
While I know the correct RegExp for this is: /^\d{13}$/, I also need it to ignore an empty field. (Because I don't want the alert to trigger in case the user switches to a different input field)
Just when I thought I had it with: /^$|\d{13}$/, it turns out that it will return an alert if there are less than 13 digits but not if there are more, unlike /^\d{13}$/ that is working fine with 14+ digits.
Can someone help me out with this? Thanks
Here's the rest of the function:
function checkNum(box) {
var re= new RegExp(/^$|\d{13}$/);
if(!box.value.match(re)) {
alert("13 numbers are required");
document.getElementById("numbers").value = '';
}
}
And here is the input field:
<input type="text" name="numbers" id="numbers" placeholder="Numbers" onFocus="this.placeholder=''" onBlur="checkNum(this); this.placeholder='Numbers'"/>
Very close!
/^$|^\d{13}$/
You just forgot to specify that the 13 digits started at the start of the string
Also, just an alternative to match(), for quicker boolean check use test()
if (!/^\d{13}$/.test(box.value)) {
alert("13 numbers are required");
document.getElementById("numbers").value = '';
}

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 to check repetition in string

I want to check the entered string in text-box for repetition. i.e. I want to accept only those String which have no repetition and can have all alphabets (CAPS ON & off) + special characters and all digits?
I tried this regexp for checking repetition
var pattern = /(\d).*\1/;
and as everything is allowed when it comes to range so i did not make any check for the same but it is not working.
Can anyone help me out with something that can make my Spin. :-)
Example - vCc##^k->Valid VbhUiu->Valid mnkOOp->Invalid fgty^^m->Invalid
var pattern = /(.).*\1/;
if (pattern.test(str)) {
alert("No repetition allowed");
} else {
alert("Looks good!");
}
DEMO

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/

Categories

Resources