Javascript checking # in email - javascript

I am trying to check an HTML input form to see if it contains an # symbol.
HTML:
<input id="emailCheck" type="text" name="uid" />
<input type="button" value="Continue" onClick="continuePlease()" />
<br>
<p id="invalidEmail"></p>
Javascript:
var at = document.getElementById("emailCheck").value.indexOf("#");
function continuePlease() {
if (at == -1) {
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
} else {
changeData();
}
}
function changeData() {
document.getElementById("title").innerHTML = "<font color=#33FF00> Information Confirmed </font>";
document.getElementById("lock").innerHTML = "<font color=red>This Account is now locked.</font>";
document.getElementById("time").innerHTML = "<font color=white> You will have 30 minutes to send the provided wallet address the correct amount of Bitcoin or the account will unlock again. </font>";
document.getElementById("daemon").innerHTML = "<font color=white> Our Bit-Daemon is watching the address 24/7, once a payment is made, the contents of the account will be sent to your Email. Thanks, Paypal Trader.</font>";
document.getElementById("pig").innerHTML = "";
document.getElementById("cow").innerHTML = "";
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
}
What's happening is that when it performs the function continuePlease() it does both the code in the IF and in the ELSE.
It should do one or the other, not both.
I think I need a better way to check for the # symbol.

move at assignment as the first line of the continuePlease. I don t think it is doing both it is always doing the else block and check the last line of the else block it is same with if block.

You can use this handy function to test that:
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
You can pass in the email using this:
var email = document.getElementById("email").value;
This function will return either true or false depending on the email string you'll provide.

Do it this way. It should work.
function continuePlease() {
var at = document.getElementById("emailCheck").value.indexOf("#");
if (at == -1) {
document.getElementById("invalidEmail").innerHTML = "<font color=red>Please enter a valid email.</font>";
} else {
changeData();
}
}

Related

How to implement Try Catch Finally Statement with form input - Javascript

I'm trying to use this to create a message that states "Please enter a number" when you hit submit on a form and there's no number in the input for "If you would like to state a specific amount type it in the box below". It's doing absolutely nothing, so I don't know what's going on. I'm still in school and this is my first class with JavaScript so I would appreciate any help you can give.
Here is the JavaScript portion:
```
// test page form exception code - Chapter 4
function verifyFormCompleteness() {
var specificAmountBox = document.getElementById("specificamount");
var completeEntry = true;
var messageElement = document.getElementById("message");
var messageHeadElement = document.getElementById("messageHead");
var validity = true;
var messageText = "";
try {
if (specificAmountBox.value == "" || specificAmountBox.value == null){
window.alert = "Please enter a number in the specific amount box";
}
}
catch(message) {
validity = false;
messageText = message;
specificAmountBox.value = ""; // removes bad entry from input box
}
finally {
completeEntry
messageElement.innerHTML = messageText;
messageHeadElement.innerHTML = "";
alert("This is happening in the finally block");
}
if (validity = true) {
return submit;
}
}
```
Here is the HTML portion:
```If you would like to state a specific amount type it in the box below:<br>
<input type="number" id="specificamount" name="specificamount">
<h1 id="messageHead"></h1>
<p id="message"></p>
<br>
<br>
```

My Validating an input field with only characters and spaces allowed. I not that familiar with regex this is just for

The contact name input area cannot be left empty and can only have characters and spaces. I'm not that familiar with regex and my online research so far hasn't come up with a simplified explanation on how to do this.
The Regex string I have come across so far is: ^\p{L}+(?: \p{L}+)*$
But I'm not advanced enough to know how to write this as script? Can anyone help.
Thanks.
var contact_name = document.getElementById('contact');
function validate() {
if (contact_name == "") {
alert("Name name must be filled out");
return false;
}
*Do I need a new function, or can I insert script here?
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
First of all, I'm not sure in your regex, so I googled a little and found this one, which looks good: /^[a-zA-Z\s]*$/. The first issue is where you're trying to compare contact_name == "": contact_name is an element, not input's value, so it should be contact_name.value === "" instead (and I recommend to use strict equality === here). And finally you can check input's value validity via regex using regex.test(contact_name.value), which returns boolean. The solution is rather simple, but if anything isn't clear - feel free to ask.
var contact_name = document.getElementById('contact');
var regex = /^[a-zA-Z\s]*$/;
function validate() {
var isValid = true;
if (contact_name.value === "" || !regex.test(contact_name.value)) {
isValid = false;
}
alert("Is valid: " + isValid)
}
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<button onclick="validate()">validate</button>
var contact_name = document.getElementById('contact');
var regex = /^[a-zA-Z\s]*$/;
function validate() {
var isValid = true;
if (contact_name.value === "" || !regex.test(contact_name.value)) {
isValid = false;
}
alert("Is valid: " + isValid)
}

Form validation woes

New to JS guy here! I feel I have understanding of what my code is doing, but it still won't work.
The bug is (supposedly) with the validation for the phone number form, I have code that -as far as I know- should work (but does not).
Note that I have not got code to validate Address, post code and CC. The Idea is that I can apply your solutions to theses, seeing as they are similar to Phone number.
Also note I did try isNaN, but it was being "weird". Hope thats not too vague, but I'm sure some of you will "know" what I'm talking about.
Here we go (Sorry if my function is a bit long, let me know if its bad practice or whatever.)
Lets stay away from blunt answers if we can? I'd like to know whats wrong so I can fix it myself, walk me through it if you have the mind to be patient :)
JS and HTML:
function detailCheck() {
var phNoLength = document.getElementById('phNo').value.length; //get value for phone number from form for checking
var cardNoLength = document.getElementById('cardNo').value.length; //get value for card number length for checking
var postCodeLength = document.getElementById("postCode").value.length //get value for post code length
var a = /^[A-Za-z]+$/;
var b = /^[-+]?[0-9]+$/;
for (var i = 0; i < 5; i++) {
details = document.getElementById("myForm")[i].value;
if (details === "") {
var i = ("Please enter ALL your details.");
document.getElementById("formTital").innerHTML=i;
return;
} else {
if(phNoLength != 7) {
var i = "Please use a phone number with a length of 7";
document.getElementById("formTital").innerHTML = i;
} else {
if(b.test(document.getElementById("phNo").value)) {
if(postCodeLength === 4){
var f_nameLength = document.getElementById('fName').value.length;
var l_nameLength = document.getElementById('lName').value.length;
if(f_nameLength < 3) {
var i = "First name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("fName").value)) {
if(l_nameLength < 3) {
var i = "Last name not long enough"
document.getElementById("formTital").innerHTML=i;
} else {
if(a.test(document.getElementById("lName").value)) {
if(cardNoLength === 4) {
if(isNaN(cardNoLength)) {
var i = "Your card number must be numbers only";
document.getElementById("formTital").innerHTML=i;
} else {
//---- End result ----//
toggleContent();
//--------------------//
}
} else {
var i = "Your card number must have four numbers";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "Please only use letters in your last name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please only use letters in your first name";
document.getElementById("formTital").innerHTML=i;
}
}
} else {
var i = "Please use a post code with a length of four";
document.getElementById("formTital").innerHTML = i;
}
} else {
var i = "only use numbers in your Phone number";
document.getElementById("formTital").innerHTML=i;
}
}
}
}
}
<form id="myForm" action="form_action.asp">
First name: <br> <input class="formInput" type="text" id="fName" name="fName"><br>
Last name: <br> <input class="formInput" type="text" id="lName" name="lName"><br>
Phone Number: <br> <input class="formInput" type="number" id="phNo" name="phNo" maxlength="7"><br>
Credit Card Number: <br> <input class="formInput" type="password" id="cardNo" name="cardNo" maxlength="4"><br>
Address: <br> <input class="formInput" type="text" id="address" name="address"><br>
Post code: <br> <input class="formInput" type="number" id="postCode" name="postCode" maxlength="4"><br>
</form>
It is not obvious when you want the validation to occur (you included a function but it is not clear whether you want it to be an event handler or not).
Your regex seems to be fine. I am including a stripped-down JSFiddle with a single input to which I attached an event handler for keyup and showed the result of .test() for your regex.
See it here.
In regards to your code, it is fairly messy. In terms of form validation. I assume you meant to display a single status message for the user, so you would want to you want to first figure out the priority of your validation. One cleaner option would be to use a function with ordered returns, for example take this pseudo-code:
function getErrorMessage(){
// if name is invalid
// return 'Your name is invalid.';
// if phone is invalid
// return 'Your phone is invalid.';
// ...
// return '';
}
Nesting so many conditional statements can lead to very messy, very non-maintainable spaghetti code. If you are new to Javascript, it is best to learn the best practices early on, as it will save you a lot of headache and facepalms in the future.
If I did not understand your question correctly, please let me know.

validating using input.value.match in javascript

I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}

Function doesn't return false in Javascript

I am trying to validate my form but when function Ive created doesn't return false, it should stop submission process but it doesn't.
my code
var emailRE = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
function formChecker() {
if (!emailRE.test(document.reservation.email.value)) {
window.alert("Your e-mail address is invalid");
return false;
}
}
I'm getting the alert so function checks email but then stops at that point
First out:
I'm not sure that document.reservation.email.value will not always work across all browsers. Over the years, I have had my frustrations using that notation.
See: Best Practice: Access form elements by HTML id or name attribute?
The following example worked well for me. Posted a fiddle here:
<form id="reservation">
Valid Email: <input type=text id="validemail" value="abc#def.com">
<label id=Result1>Result is: </label>
<br>
Invalid Email: <input type=text id="invalidemail" value="abc#def.">
<label id=Result2>Result is: </label>
</form>
var emailRE = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
function formChecker(oElement) {
if (!emailRE.test(oElement)) {
window.alert("Your e-mail address is invalid");
return false;
} else {
window.alert("Your e-mail address is valid");
return true;
}
}
document.getElementById("Result1").innerHTML = "Result is: " + formChecker(document.forms["reservation"].validemail.value);
document.getElementById("Result2").innerHTML = "Result is: " + formChecker(document.forms["reservation"].invalidemail.value);
See working example here: http://jsfiddle.net/vNmt4/1/

Categories