check for correct email in form [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
I am trying to use this javascript to check for a valid email, but what I don't need it to do is check to see if the field is blank in the form in case someone doesn't have an email address (don't ask).
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_email(email,"Not a valid e-mail address.")==false)
{email.focus();return false;}
}
}
I tried to adjust the apos<1 to less than 1 or nothing at all and that didn't seem to work.

Just check whether it is empty, and otherwise apply your email regex/validation function on it.
Also, you should a) not use with and b) not alert from the test function.
function test_email(address) {
var atpos = address.indexOf("#"),
dotpos = address.lastIndexOf(".");
if (atpos < 1) // "#" at position 0 or not found (-1)
return false;
if (dotpos-atpos < 2) // last "." before position 2 or not found (-1)
return false;
if (atpos > dotpos) // last "." before the "#"
return false;
return true;
}
function validate_form(thisform) {
var input = thisform.email;
if (input.value) // != ""
if (!test_email(input.value)) {
alert("Not a valid e-mail address.");
email.focus();
return false;
}
}

A regular expression is probably the best approach, and a previous question has a great regular expression to use, though there are more complex and complete ones available. Validate email address in JavaScript?
Taking that regular expression and fitting into your code, you'd have a function looking something like this
function validate_email(field,alerttxt) {
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,}))$/;
if (re.test(field)) {
return true;
} else {
alert(alerttxt);
return false;
}
}

Related

Check if key is in array-JavaScript

I have this JavaScript code
function checkTextField() {
var textVal = document.getElementById("textfield").value;
if (textVal == '', textfield.value.length <= 31)
{
alert('Wrong Key-Code. Key-Code must have 32 characters!');
}
else //Its all about how to decrypt a database file called ,,Salam Horia Allah,,!(good luck hackers)
{
{
var text = document.getElementById("textfield").value;
if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"
)
{
location.href = "http://79.115.70.31:8521/InWork/"
}
else {
alert("Wrong Key")
}
}
}
}
and here is what happen:
i have a textbox and a button,when i insert a key from if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
And when someone press that button, I want that script to check if one of that keys are in text field, if is true the request will send to another page, if is not true, show an alert.
But my problem is, whatever I write in that textbox it send me to that page, also I got an alert if textbox have <31 characters.
The comma operator works inside of an if clause, but it takes the last value, not a logical OR, which is here required.
(An input returns always a string and if empty, the string length is zero. A check for emptiness and a check for a length which is smaller than a value is superfluous, because the length check includes a zero length as well.)
if (textVal == '' || textfield.value.length <= 31)
// ^^
Beside that, I suggest to use an array for the valid keys for checking and check only if the value is in the array, then proceed or give an alert.
Another point is to assign the value of the input only once and use it in the whole function with the variable. Do not use a mixed style with a variable and document.getElementById("textfield").value together.
function checkTextField() {
var keys = ["3e6898f92134d05408dfed30b268d9d6", "fa0f82cc02a6cdc35072ee5ce2b0c379", "6a1df566fcaabca717aa1b81c3e0bd31", "dc0beea186c5f5c2110bedbeccc5a7aa", "1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40", "08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c", "ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11", "23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6", "teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy", "SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"],
text = document.getElementById("textfield").value;
if (keys.indexOf(text) !== -1) {
location.href = "http://79.115.70.31:8521/InWork/";
} else {
alert("Wrong Key");
}
}
Well you need to compare you tex with each key available so
function checkTextField() {
var textVal = document.getElementById("textfield").value;
var yourKeys =[ "3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"];
if (textVal == '', textfield.value.length <= 31)
alert('Wrong Key-Code. Key-Code must have 32 characters!');
else {
var text = document.getElementById("textfield").value;
var i = yourKeys.length;
while(i--){
if(text == yourKeys[i] )
location.href = "http://79.115.70.31:8521/InWork/"
else
alert("Wrong Key")
}
}
}

/ operator (or some other part of the code) doesn't seem to work

I wrote a simple code in javascript that was supposed to validate the length of a phone number inputed in an html form (check if it consists of 10 digits- as it is in my country).
So here's the function:
function check_tel(){
var tel=document.LpData.phone.value;
var i=0;
for(;i<10;i++){
tel/=10;
if(tel==0){
alert("unvaild phone number- too short");
return false;
}
}
if(tel>0){
alert("unvaild phone number- too long");
return false;
}
return true;
}
But it always outputs that the number is too long (i>10).
I already checked the value of "tel" variable before it enters the loop and everything is right.
I also tried it with a "while" instead of "for" loop.
So I concluded it's because of the "/" operator which doesn't work (although I still don't understand how it's possible) or it has something to do with the type of tel...
So what is the problem and how to fix it?
Thanks in advance!
Every input value is always a string. Using the divide operator on a string is not what you wanted. So you may convert the phonenumber to an int:
function check_tel(){
var tel=parseInt(document.LpData.phone.value,10)||0;
for(var i=0;i<10;i++){
tel/=10;
if(tel<1){
alert("unvaild phone number- too short");
return false;
}
}
tel/=10;
if(tel>1){
alert("unvaild phone number- too long");
return false;
}
return true;
}
also note that 123456789/10000000 is not 0...
and by the way, it is much easier to simply check for tel.length...
The best practice to do these things is to use a Regular Expression(Regex).
/^\d{10}$/ is a JS regex to check if the number is a 10 digit number.
function check_tel()
{
var tel = document.LpData.phone.value;
var teleRegex =/^\d{10}$/;
if(!teleRegex.test(tel)){
alert("invalid phone number")
}
else{
//do your thing
}
}
Possible work-around is
function check_tel()
{
var tel=document.LpData.phone.value;
if(tell.length == 0 || tell.length > 10){
alert("invalid phone number");
return false;
}
return true;
}
Try var tel = parseInt(document.LpData.phone.value); instead of var tel = document.LpData.phone.value;

Text Box Integer Validation

I need to create a code in HTML/Javascript that will allow a user to enter an answer to a maths question and then the site needs to validate whether that answer is correct.
Been playing around for a few hours and researched the web but not found anything close.
Any help is appreciated!!
You could use javascript for validation,
Look at this example.
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
checking if value of a textfield is integer in javascript
Javascript validation
function isInteger(number) {
var getVal = parseInt(number);
if (number.length == 0 || getVal == Number.NaN || getVal <= 0) {
return false;
}
return true;
}

Required only one dot at the end of nameserver

The regex below works nice except I need only one dot (.) at the end for nameserver. For example if user submit ns1.hello.com there will be error. Accepted format is with dot at the end like this ns1.hello.com. Help me please. Thank you.
<script type="text/javascript">
function validSubdomain() {
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+\.$/;
var val = document.getElementById("nameserver").value;
var val2 = document.getElementById("nameserver2").value;
if(val == '' && val2 == ''){
alert("Please fill in the name server");
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
if(val == ''){
alert("Please fill in the name server 1");
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
if(val2 == ''){
alert("Please fill in the name server 2");
document.forms['namaform'].elements['nameserver2'].focus();
return false;
}
var parts = val.split('.');
var parts2 = val2.split('.');
if (parts.length < 3)
{ alert('invalid nameserver format')
document.forms['namaform'].elements['nameserver'].focus();
return false;
}
else if (parts2.length < 3)
{ alert('invalid nameserver 2 format')
document.forms['namaform'].elements['nameserver2'].focus();
return false;
}
if( !re.test(val)) {
alert("invalid nameserver 1 format");
return false;
}
else if( !re.test(val2)) {
alert("invalid nameserver 2 format");
}
else{namaform.submit();}
}
</script>
Two things wrong with:
if(re.test(val && val2)) {
alert("valid format");
}
if(!re.test(val && val2)) {
alert("invalid format");
}
First of all, have you never heard of else? It's there specifically so you don't have to repeat a test in the negative.
Second, you are trying to && together the two string and then passing the resulting boolean to re.test(). Since a boolean converts to the string "true" or "false" it will never ever match.
Change to:
if( re.test(val) && re.test(val2)) {
alert("valid format");
}
else {
alert("invalid format");
}
Also note that your regex is wrong. It would accept a..b as input, which is clearly not valid. Try this instead:
var re = /^([a-z0-9-]+\.)+[a-z]{2,3}\.$/i;
This will broadly match most domains with unlimited number of subdomain levels, provided there's a . at the end.
EDIT to disallow - at the front of a section:
var re = /^([a-z0-9][a-z0-9-]*\.)+[a-z]{2,3}\.$/i;
It sounds like you're just saying that this:
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9]$/;
needs to be this:
var re = /^[a-zA-Z0-9][a-zA-Z0-9.-]+\.$/;
?
If you want to match a special character in a regex (also referred to as 'metacharacters') you need to escape it with a backslash. So, just before the $ in your regex, include
\.
to match the dot at the end of the string.

javascript validation to check # at start of user input: not email validation

I have to check whether a form field contains '#' at start of user input & is it contains it at all. It works fine for checking if its at start of the string. But when I add checking whether input contains '#' at all or not. It fails. Here is my code
function email_valid(field)
{
var apos=field.update.value;
apos=apos.indexOf('#');
if (apos>0 ||((apos.contains('#')== 'FALSE')))
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
EDIT
This function in this form is checking both if # is at 1st place & 2ndly is it in the input at all or not.
function #_valid(field)
{
var ref=field.update.value;// I needed ref 4 other things
var apos=ref.indexOf('#');
if (apos>=0 )
{
if (apos==0)
{
return true;
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
}
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
} }
Consider:
var apos = value.indexOf('#');
if (apos >= 0) {
// was found in string, somewhere
if (apos == 0) {
// was at start
} else {
// was elsewhere
}
} else {
// not in string
}
and
var apos = value.indexOf('#');
if (apos == 0) {
// was at start
} else if (apos > 0) {
// was elsewhere
} else {
// not in string
}
Why not just
if (apos !== 0) { /* error; */ }
The "apos" value will be the numeric value zero when your input is (as I understand it) valid, and either -1 or greater than 0 when invalid.
This seems like a strange thing to make a user of your site do, but whatever. (If it's not there at all, and it must be there to be valid, why can't you just add the "#" for the user?)
You can just check to make sure that apos is greater than -1. Javascript's indexOf() will return the current index of the character you're looking for and -1 if it's not in the string.
edit Misread a bit. Also make sure that it's not equal to 0, so that it's not at the beginning of the string.
function email_valid(field)
{
var fieldValue =field.update.value;
var apos = apos.indexOf('#');
if (apos > 0 || apos < 0)//could also use apos !== 0
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
apos is the value returned by indexOf, it will be -1 if there is no # in the user input. It will be 0 if it is the first character. It will be greater than 0 if the user input contains an # . JavaScript has no contains method on a String.
Try:
function email_valid(field) {
//var apos=field.update.value;
var apos = field;
//apos=apos.indexOf('#');
apos = apos.indexOf('#');
if( (apos < 0) ) {
//alert('plz enter valid input');
alert('false');
} else {
alert('true');
}
}
email_valid('blah');
Checks for # anywhere. Or, if you want to check for # just at the beginning, change if( (apos < 0) ) { to if( (apos == 0) ) {. Or, if you want to make sure it's not at the beginning, then if( (apos > 0) ) {.
apos will be -1 if the string was not found. So your code should be as follows:
function email_valid(field)
{
var apos=field.value;
apos=apos.indexOf('#');
if (apos<=0) // handles '#' at the beginning and not in string at all.
{
alert('plz enter valid input');
return false;
}
else
{ return true; }
}
I also changed your initial assignment to remove the .update portion as that would cause it to fail when field is a reference to an input.
In the second if condition, apos is a number, not a string.
You're trying to write
if (field.update.value.charAt(0) == '#' && field.update.value.indexOf('#', 1) < 0)
Learn about Regular expressions if you haven't already. Then lookup Javascript's String#match. There is no need to find wether the input starts with an "#" as if it contains an "#" that will also return true if the "#" is at the start of the string.
Also, for free, return true and return false are generally bad style. Just return the thing you passed to if (that evaluates to a boolean).
All in all:
function validate_input(str) {
return str.match(/#/);
}
I reccomend passing the function a string (field.value or some-such) rather than the field itself as it makes it more generic.
Update: revised answer based on comments. code below will only return true if the value contains an "#" symbol at the first character.
If this is a JavaScript question, then this should be fine.
function email_valid(field){
var apos=field.update.value;
if(apos.indexOf('#') != 0){
alert('plz enter valid input');
return false;
} else {
//field contains an '#' at the first position (index zero)
return true;
}
}
That said, your parameter "field" if it actually refers to an input field element, should only require this code to get the value (e.g. I'm not sure where the ".update" bit comes into play)
var apos = field.value;
I would also rename this function if it isn't doing "email validation" to something a little more appropriately named.

Categories