First i'd like to mention that i've been researching about this for few days and although i found some answers that should have been helpful i was unable to use them correctly due to the fact that i am not that much into programming yet and got no experience and might be missing something.
Straight to the point, i have a registration form and i need field validation i already have the one that validate email and empty fields for others but i need to add to the code a part that would reject numerical entries in name fields and alphabetical characters for ID field and to limit the length of a field.
Let's start with the Name field which i want to allow alphabetical characters only here is my current code:
{
var fn=document.forms["myForm"]["FirstName"].value;
if (fn==null || fn=="")
{
alert("First name must be filled out");
return false;
}
And that's my ID field which i want to limit to numerical entries only
var id=document.forms["myForm"]["ID"].value;
if (id==null || id=="")
{
alert("ID must be filled out");
return false;
}
I want to a couple of lines that would limit entries to a specific number of characters as well, how do i do that?
To check for a string length in Javascript you can use the .length method:
// this checks if the fn length is more than 10
if (fn.length > 10) {
}
To check if a value is numeric you can parse it and make sure that returns a valid output:
// This checks if id is not a valid integer
if (isNaN(parseInt(id)) {
}
To check if a value is alphabetical only you have to make sure the characters in it fall within the alphabets range, you can add a function that checks for that:
// This loops on every character of value and makes sure it is part of the letters string
function isAlphabetical (value) {
var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < value.length; i++) {
if (letters.indexOf(value.charAt(i), 0) == -1) {
return false;
}
return true;
}
}
And then call it from your if statement:
// This checks if fn is not alphabetical
if (!isAlphabetical(fn)) {
}
Related
I am trying to make the JavaScript have a min length on the username characters. The username has to have at least 5 characters in the name. So far, I can type in the username but, still get the message we need 5 characters even if we have more or less, the only time that does not happen is when I don't type anything in. I don't quite understand why.
// version 1
let y = document.querySelector("#nick2").value; {
if(y== 0)
for(y.length=0; y.length>5; y.length++);
{
console.log("need at least 5 letters in the username ");
}
//Version 2
let y = document.querySelector("#nick2").value; {
if(y== 0)
if(y.value.length !=5){
y.value="";
input=y.value
if(input.length<5){
console.log("need at least 5 letters in the username");
}
}
What am I doing wrong?
You can check the length of your input element by calling a function within your input element's onkeyup method.
Something like this:
function check(item) {
let y = item.value.trim(); // trim() removes any extra whitespace
if(y.length < 5) {
console.log("Need at least 5 letters in username");
} else {
console.log("You've entered 5 or more characters for username");
}
}
<!-- You can pass the element as 'this' to the function -->
<input type="text" value="" onkeyup="check(this)" />
Note: If you want to allow whitespace characters (spaces) to be a valid input then remove trim().
I have a number of HTML inputs in a website. They are inside a form, but the form is not submitted to the server. Rather, values of the assorted inputs (number inputs, text inputs, and check boxes) are used to ultimately 'stitch together' a product code based on the inputs and selected options. (using JavaScript)
My problem is this: while the number input
<input type='number'/>
only allows a number value when used in a server-side submit, I am using JavaScript to check the assorted values of the different inputs. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input becomes outlined in red, but it still allows the function that stitches together the product code to be called.
What I need is a way to detect if a given string contains an alphabetical character, instead of just numbers. My idea was something like this:
<input type='number' id='inp' />
<script>
input=document.getElementById('inp');
val=input.value;
checkforletters(val);
input.onchange=function(){
if(checkforletters){
//resetting the value to blank if there is an alphabet character in the string
input.value='';
}
}
</script>
You'll notice that there is a function in there called
checkforletters()
I have not written it. This function would check and see if there is an alphabet character inside the string that comes from the value of my input; and if there is, the function would return true.
This function is what I need. The rest of the code resets the value of the input to blank if there is an alphabet character.
So, to summarize, what I need is a function that, when passed a string as an argument, returns true if there is an alphabet letter in it, and false otherwise.
Note
Please use pure JavaScript only. No jQuery or other libraries/frameworks.
You can use isNaN() function to make your own function that check if the given string is numeric :
//Will return true if the given string is number, false if is contain characters
function isNumeric(yourString){
return !isNaN(yourString)
}
Hope this helps.
My problem is this: while the number input only allows a number value when used in a server-side submit, I am using JavaScript to check the assorted values of the different inputs. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input becomes outlined in red, but it still allows the function that stitches together the product code to be called.
You can utilize the built in HTML5 constraint validation with JavaScript. This means that instead of having to check whether the value is valid, the value can never be invalid to begin with.
The following example will disallow any invalid input at the user level. It does this by checking the validity then storing the value for future use if it is valid or, if the value is not valid, setting the value to the previously stored valid value if there is one, an empty string if not.
This means that the value can never be invalid.
<input type="number"
oninput="(validity.valid&&(dataset['prev']=value))||(value=dataset['prev'])">
The following is the same method, without using inline JavaScript
document.getElementById('test').oninput = function() {
if(this.validity.valid) this.dataset['prev'] = this.value;
else this.value = this.dataset['prev'];
}
<input type="number" id="test">
So, to summarize, what I need is a function that, when passed a string as an argument, returns true if there is an alphabet letter in it, and false otherwise.
If a number input's value is invalid, it will return an empty string.
This means that you cannot compare the returned value to check it's validity, because if it is in fact invalid the returned value will be an empty string.
The following example shows that even if the value is invalid, checking it with isNaN won't show you that, nor will any of the other methods mentioned here.
<input type="number" oninput="document.getElementById('value').textContent = value; document.getElementById('isnum').textContent = !isNaN(value)"><br>
Returned Value: <span id="value"></span><br>
Is a number: <span id="isnum"></span>
If you really want to validate the input element while running your script, you can check the input element's validity at that time.
var test = document.getElementById('test');
document.getElementById('button').onclick = function(e) {
if(!test.validity.valid) {
alert('Its Invalid!');
} else {
alert('Its valid!');
}
}
<input id="test" type="number"><button id="button">Check It</button>
Alternatively, if your input elements are inside a form and you run your script on the form submission event, it will automatically validate for you, and disallow submission unless the value is valid.
var test = document.getElementById('test');
document.getElementById('form').onsubmit = function(e) {
e.preventDefault();
alert("Its valid!"); // this will only happen if the inputs are valid.
}
<form id="form"><input id="test" type="number"><button>Check It</button></form>
Use a regular expression that matches any non-digits.
var myString = 'aaaaa1';
var reg = new RegExp(/\D+/);
console.log(reg.test(myString));
// true
here is simplest way- handle onkeyup:(http://jsfiddle.net/vittore/g7xe0drp/)
var inp2= document.getElementById('inp2')
inp2.onkeydown = onlyNumbers
function onlyNumbers(e) {
console.log(e)
if (e.which <=49 || e.which >=57) {
e.preventDefault()
return false;
}
}
Check that string contains only numbers (\d):
function checkforletters(val) {
var pattern = /^\d+$/;
return pattern.test(val);
}
If you need other characters beside numbers instead of \d use [\d,-] (, and - are characters that you want to allow).
Please use this to check for alphabets or special characters in your input:
checkforletters(val){
var pattern = /[\D]+/
if (pattern.test(val)) {
// val contains a non-digit character, it contains alphabet or special character
}
else{
// val only contains digits
}
}
pattern.test(val) will only return true if val contains alphabet
You could try this I found on the filter page of developer mozilla org.
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}
array filter
Of course you will need to rework it a little to make isString(), you could try typeof(obj) === 'string' && isNaN(obj).
you can get a list of obj from a string with theString.split('')
For example:
let s = 'Is this 1 or 2 and not 3 strings? .! : '
let c = s.split('')
let d = c.map((c,i) => {
let v = typeof(c) === 'string' && isNaN(c) ? 'string': 'not-string'
return {c, v}
})
console.log(d)
I am trying to figure out if a user has entered an email id or a phone number. Therefore i would like to check if the string starts with +1 or a number to determine if it is a phone number . If it is not either i come to the conclusion it is an email or i could check if it starts with a alphabet to be sure. How do i check this . I am horrible with regex if that is the soln .
You can do this with RegEx, but a simple if statement will work as well, and will likely be more readable. If an # character is not present in the string and the first character is a number, it is reasonable to assume it's a phone number. Otherwise, it's likely an email address, assuming an # is present. Otherwise, it's likely invalid input. The if statement would look like this:
if(yourString.indexOf("#") < 0 && !isNaN(+yourString.charAt(0) || yourString.charAt(0) === "+")) {
// phone number
} else if(yourString.indexOf("#") > 0) {
// email address
} else {
// invalid input
}
if (!isNaN(parseInt(yourstrung[0], 10))) {
// Is a number
}
Just do the following:
if ( !isNaN(parseInt(inputString)) ) {
//this starts with either a number, or "+1"
}
Might I suggest a slightly different approach using the regex email validation found here?
if(validateEmail(input_str)) {
// is an email
} else if(!isNaN(parseInt(input_str))) {
// not an email and contains a number
} else {
// is not an email and isn't a number
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
This way you can check a little more thoroughly on what the input actually is, rather than just guessing it's one or the other.
I want to filter multiple zip codes in an input, there should be at least 2 zip SEPARATED by a COMA, I am trying to validate them in javascript with the following code but it's now filtering, the submit send the form to the next page without error, anyone can help?
<script>
function validateMULTIZIP() {
if(!/\d{11,}/.test(document.zipad.textfield.value) && document.getElementById('single').checked==false))
{
alert( "There should be a least two Zip codes separated by a coma." );
document.zipad.textfield.focus() ;
return false;
}
return true;
}
</script>
This will check for two 5-digit numbers separated by a comma
^\d{5},\d{5}$
But, you said at least two, so that means it needs to be a little more flexible to accommodate more. If the user enters 12345,12345,12345 it needs to be valid.
^\d{5}(?:,\d{5})+$
What if the user adds a space after the comma? Such as 12345, 12345. This is perfectly valid, so let's make sure our validator allows that.
^\d{5}(?:,\s*\d{5})+$
Oh, and zip codes can have an optional -1234 ending on them, too (known as ZIP+4. Maybe you want something like this
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
Now strings like this would be valid
12345
12345, 12345,12345
12345, 12345-9999, 12345
As a bonus, let's say 12345, 12345 is invalid because it has the same zip code twice. Here's how we'd fix that
(?:(\d{5}),?)(?!.*\1)
And here's the ZIP+4 version
(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-))
This one has a little added complexity because of possibility of (e.g.,) 12345, 12345-9999. This is valid but because 12345 can appear more than once, it makes sure that a 5-digit zip code can't be invalidated by a unique 9-digit zip code.
Note these duplicate-checking regexps do not enforce the minimum of two unique zip codes. If you want to check for duplicates you'd need to combine the two.
var valid5DigitZipCodes = function(str) {
if (! /^\d{5}(?:,\s*\d{5})+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}),?)(?!.*\1)/.test(str)) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
And here's the ZIP+4 variant if you want to support that
var valid9DigitZipCodes = function(str) {
if (! /^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-)).test(str) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
Assuming (from your code) that ZIP code contains five digits and no other characters, you could use:
/\d{5},\d{5}/.test(document.zipad.textfield.value)
You regex: \d{11,} means "any digit, eleven times or more", that's why it's broken.
Another Solution without using regex would be splitting zip Codes by comma then check for the size of the resulting array.
Sample code:
<input type="text" id="in"></input>
<button onclick="validate()">Click</button>
JS
function validate() {
var inp = document.getElementById("in");
var content = inp.value;
var correct = validateZipString(content);
if (correct) {
alert("ok");
} else {
alert("not ok");
}
}
function validateZipString(zipString) {
var zipCodes = zipString.split(',');
if (zipCodes.length < 2) return false;
for (var i = 0; i < zipCodes.length; i++) {
//validate each zipCode if required
}
return true;
}
here is a working jsfiddle http://jsfiddle.net/VcNd9/3/
For anyone else interested in the variant that also matches 1 zip or more rather than two or more. Simply change the + quantifier for * at the end of the expression.
From:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
To:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$
For example:
<input type="text" inputmode="numeric" pattern="^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$">
Goal:
I dont wanna retrieving any data if the input data contain any alphabet.
Problem:
If I have input data "23w" in variable ddd, the process on convertion is accceptable to be "23" in the variable currentvalue.
I don't want it to be converted into number if the input data contain
any alphabet.
The sourcecode is writtin in jQuery and if possible it would be great to retreive the new solution in jQuery.
// Fullmetalboy
var ddd = $('#field_hourInput').val();
var currentValue = parseInt(ddd);
// Validating message
if(currentValue <= 0)
{
alert("Value must be positiv");
nonError = false;
}
else if( (isNaN(currentValue)) && (ddd != "") )
{
alert("value must contain numbers");
nonError = false;
}
else if( (isNaN(currentValue)) && (ddd == "") )
{
alert("value must contain value in the textbox");
nonError = false;
}
parseint() will return a number if the string begins with one, even if there is non-numbers following it. For example: http://jsfiddle.net/uQztw/
Probably better to use a regex. Something like
http://jsfiddle.net/uQztw/1/
You can use regex to validate that. Using regex with jquery. And using regex
[\d]
which will match any digit should do the trick.
Another way to convert string to int is Number(ddd), it does what you expect. But you could also check ddd through a regular expression, which feels better to me.
regexp-test: /^\d+$/.test(ddd)