Form validation for username and Email in java script - html

I'm trying to validate the value in my name element and email address element.
but the below code is not providing the proper validation and my code is still jumping to my php file with wrongs inputs in it.
can anybody please provide me some guidance on this?
var letters = /^[A-Za-z]+$/;
var mailformat = ^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$;
if( document.addform.First_name.value.match(letters)) {
return true;
}
else {
alert( "Username must have alphabet characters only" );
document.addform.First_name.focus() ;
return false;
}
if( document.addform.email.value.match(mailformat) ) {
return true;
}
else {
alert( "You have entered an invalid email address!" );
document.addform.email.focus() ;
return false;
}

You need to return true if both conditions are met, not just one of them.
function validateFormInput () {
let yourUsernameRegEx = new RegExp(...);
let yourMailRegEx = new RegExp(...);
if (!document.addform.First_name.value.match(yourUsernameRegEx)) {
// Other code here (alerts, popups, etc.) ...
return false;
}
if (!document.addform.email.value.match(yourMailRegEx)) {
// Other code here (alerts, popups, etc.) ...
return false;
}
return true;
}

Related

using condition in jquery onclick button

Im trying to confirm if the password strength is strong or weak and is the password is strong and when I submit it should have alert message like "You Have Strong Password" and when its weak "Invalid Password"
This is what I am now.
function checkPasswordStrength() {
var passwordStrength = false;
var number = /([0-9])/;
var alphabets = /([a-zA-Z])/;
var special_characters = /([~,!,#,#,$,%,^,&,*,-,_,+,=,?,>,<])/;
if ($('#password').val().length < 8) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('weak-password');
$('#password-strength-status').html("Weak (should be atleast 8 characters.)");
} else {
if ($('#password').val().match(number) && $('#password').val().match(alphabets) && $('#password').val().match(special_characters)) {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('strong-password');
$('#password-strength-status').html("Strong");
return passwordStrength = true;
} else {
$('#password-strength-status').removeClass();
$('#password-strength-status').addClass('medium-password');
$('#password-strength-status').html("Medium (should include alphabets, numbers and special characters.)");
}
}
}
$('#btn-submit').click(function () {
if (passwordStrength == false) {
alert("INVALID PASSWORD");
} else {
alert("You have Strong PASSWORD");
}
</script>
its for Educational Purpose only im just starting jquery..
thank you in advance..
You need to call the function instead of just checking your variable. So rather do
$('#btn-submit').click(function () {
if (checkPasswordStrength() === false) {
instead of
$('#btn-submit').click(function () {
if (passwordStrength == false) {
Then, instead of return passwordStrength = true; you should do just passwordStrength = true and add a return passwordStrength to the very end of your function so it will return either false or true.
It looks like the variable scope is incorrect. var passwordStrength should be put outside of the checkPasswordStrength function.
var passwordStrength
function checkPasswordStrength() {
....

Parameter passing for multiple text fields that are gathered in an array?

So, I have a question. I'm currently working an an education program that teaches basics on cell organelles. I have lines pointing to each organelle, in which I want to have the user be able to input what each organelle name is (like a diagram). When the user has completed the work properly, I will display the next button.
However, in order to give the user the ability to proceed, I need a way of tracking whether or not a student's answers are correct. I am using parameter passing for this.
I would like to be able to return either true/false. If all answers are returned true, the user may advance. If even one answer is wrong, a message displays.
How do I use parameter passing to determine if a users answers are right/wrong? The textfields are in an array as well...
Here is the code.
Thanks!
-Zero;
import flash.events.MouseEvent;
var organelleInput:Array=[F18nucleolusInput_txt, F18nucleusInput_txt, F18erInput_txt, F18golgiInput_txt, F18vacuoleInput_txt, F18chloroplastInput_txt, F18lysosomeInput_txt, F18mitochondriaInput_txt];
F18next_btn.visible=false;
F18next_btn.addEventListener(MouseEvent.CLICK, F18goToFrameNineteen);
F18back_btn.addEventListener(MouseEvent.CLICK, F18goToFrameSix);
checkMyWork_btn.addEventListener(MouseEvent.CLICK, checkAnswers);
function checkAnswers(event:MouseEvent):void
{
var answer:String;
var correctAnswers:Boolean;
var incorrectAnswers:Boolean;
answer = organelleInput[i];
correctAnswers=checkCorrectAnswers(answer);
for(var j:int=0; j<organelleInput.length; j++)
{
organelleInput[j].restrict="a-z";
if(correctAnswers==true)
{
F18output_txt.text="Well done!";
F18next_btn.visible=true;
checkMyWork_btn.visible==false;
}
if(correctAnswers==false)
{
F18output_txt.text="One of them seems to be wrong. Try again.";
}
}
}
function F18goToFrameNineteen(event:MouseEvent):void{
gotoAndStop(19);
}
function F18goToFrameSix(event:MouseEvent):void{
gotoAndStop(6);
}
function checkCorrectAnswers(s:String):Boolean
{
if(F18nucleolusInput_txt.text=="nucleolus"){
return true;
}
return false;
if(F18nucleusInput_txt.text=="nucleus"){
return true;
}
return false;
if((F18erInput_txt.text=="endoplasmic reticulum")||(F18erInput_txt.text=="er")){
return true;
}
return false;
if((F18golgiInput_txt.text=="golgi body")||(F18golgiInput_txt.text=="golgi apparatus")){
return true;
}
return false;
if((F18mitochondriaInput_txt.text=="mitochondria")||(F18mitochondriaInput_txt.text=="mitochondrion")){
return true;
}
return false;
if((F18lysosomeInput_txt.text=="lysosome")||(F18lysosomeInput_txt.text=="lysosomes")){
return true;
}
return false;
if(F18vacuoleInput_txt.text=="vacuole"){
return true;
}
return false;
if((F18chloroplastInput_txt.text=="chloroplast")||(F18chloroplastInput_txt.text=="chloroplasts")){
return true;
}
return false;
}
You can check Array of TextFields vs Array of Arrays:
var Correct:Array = [
["nucleolus"],
["nucleus"],
["golgi body", "golgi apparatus"],
["mitochondria", "mitochondrion"]
];
var Answers:Array = [T1, T2, T3, T4];
// Returns true if all answers are correct.
function allCorrect():Boolean
{
for (var i:int = 0; i < Answers.length; i++)
if (!oneCorrect(Answers[i], Correct[i]))
return false;
return true;
}
// Returns true if answer is on the Array of correct answers.
function oneCorrect(source:TextField, target:Array):Boolean
{
return target.indexOf(source.text.toLowerCase()) > -1;
}

How to remove carriage return char after it's pressed?

I have a textarea which is restricted to input only numbers. I want to remove carriage return char after user presses enter key. Here's my code:
// Change tempo
function changeTempo(event:KeyboardEvent):void {
if (event.charCode == 13) {
// Some code here
}
// Remove enter char
removeCarriageReturnsAndNewLines(tempo_txt.text);
}
function removeCarriageReturnsAndNewLines($myString:String):String {
var newString:String;
var findCarriageReturnRegExp:RegExp = new RegExp("\r", "gi");
newString = $myString.replace(findCarriageReturnRegExp, "");
var findNewLineRegExp:RegExp = new RegExp("\n", "gi");
newString = newString.replace(findNewLineRegExp, "");
return newString;
}
I would say the easiest way is to listen to text input, something like this:
var t:TextArea = this.ta; //ta is on the timeline
t.restrict = "0-9"; //restricts the input only to numbers
t.addEventListener(TextEvent.TEXT_INPUT, onTextInput, true); //use capture phase to be able to prevent the default behavior (text input)
function onTextInput(e:TextEvent):void {
if(e.text.indexOf("\n") > -1) {
e.preventDefault(); //prevent the default behavior of the field
}
}
I cannot test this right now but I guess it should work without problems.

Actions Script 3.0 if else statements

need to do several things by it's click event. I'm a beginner to this, so is there any other way to write this code? by clicking this button, it goes to next frame and according to statement several buttons will be visible or not. I wrote the code this way and it says there are syntax error, but I couldn't find any. Hope you guys understand this and will help me. :) Thank you!
review_btn.addEventListener(MouseEvent.CLICK, review1)
function review1(event:MouseEvent):void{
if(rvw1 == "Correct"){
gotoAndStop(3627);
help1.visible = false
}
else{
gotoAndStop(3627);
help1.visible = true
}
}
review_btn.addEventListener(MouseEvent.CLICK, review2)
function review2(event:MouseEvent):void{
if(rvw2 == "Correct"){
gotoAndStop(3627);
help2.visible = false
}
else{
gotoAndStop(3627);
help2.visible = true
}
}
review_btn.addEventListener(MouseEvent.CLICK, review3)
function review3(event:MouseEvent):void{
if(rvw3 == "Correct"){
gotoAndStop(3627);
help3.visible = false
}
else{
gotoAndStop(3627);
help3.visible = true
}
}
review_btn.addEventListener(MouseEvent.CLICK, review4)
function review4(event:MouseEvent):void{
if(rvw4 == "Correct"){
gotoAndStop(3627);
help4.visible = false
}
else{
gotoAndStop(3627);
help4.visible = true
}
}
review_btn.addEventListener(MouseEvent.CLICK, review5)
function review5(event:MouseEvent):void{
if(rvw5 == "Correct"){
gotoAndStop(3627);
help5.visible = false
}
else{
gotoAndStop(3627);
help5.visible = true
}
}
I'll take an attempt at it. It looks like the only difference is that in each method you need to match up "helpX".visible with "rvwX" equals the string "Correct", where X is a number from 1-5. The gotoAndStop() frame is the same regardless. Also, that all five are meant to be off the same button. I'm going to take an assumption that the clips 'help' are movieclips defined on the stage else if they are from something else I would store them in an array for looping through instead of 'building' the name and finding the reference that way just for clarity.
function review(event:MouseEvent):void {
for(var counter:int = 1; counter < 6; counter++){
this["help" + counter].visible = (this["rvw" + counter] != "Correct");
}
this.gotoAndStop(3627);
}
review_btn.addEventListener(MouseEvent.CLICK, review);
I think you have to do a class with 2 fields: "help" and "rvw" (let me call it "Switcher"). Also it may contain a function of setting visibility (may, not must, this function can also be in your main class):
Switcher.as:
import flash.display.MovieClip;
public class Switcher {
private var help:MovieClip;
private var rvw:String;
public function setVisibility() {
help.visible = !(rvw == "Correct");
}
}
Then you have to make an array of Switcher's objects in your main class and to use only one "review" handler:
function review(event:MouseEvent):void {
for each(var sw:Switcher in switchersArray) {
sw.setVisibility();
}
this.gotoAndStop(3627);
}
The code from previous answer will work correctly, but IMHO, creating an Array (or Vector) of similar objects is better than doing lots of help1, help2, help3 etc variables.

Windows 8 Javascript Promises

I have the following function:
function pickContacts() {
var output = "";
// Create the picker
var picker = new Windows.ApplicationModel.Contacts.ContactPicker();
picker.commitButtonText = "Select";
var emailsPromise = new WinJS.Promise(function () {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
});
return emailsPromise;
};
This gets me a list of e-mail addresses from selected contacts. So next I want to use that; here's my code:
document.getElementById("findEmail").addEventListener("click", function () {
var emailAdd = document.getElementById("email");
pickContacts().done(function (emails) {
emailDets.value = emails;
});
});
But I'm not getting the return value from pickContacts (which I've determined is actually returned). I'm guessing that there's something wrong with the way I'm handling the returned promise, but I can't seem to debug it (trying to step into it just exits the function).
What am I doing wrong?
You don't need to create a new promise--just return the promise from pickMultipleContactsAsync.then. The promises spec says that the return value from .then is another promise that's fulfilled when your completed handler finishes, and the fulfillment value is the return value of the completed handler. So you can just do this:
return picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
The other way works, but just creates yet another promise that isn't needed, and makes your code a little more complex.
You'll have to pass the completed callback as a parameter of your promise function and then call it with the results you want to pass. Esseintially:
var emailsPromise = new WinJS.Promise(function () {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
return output;
} else {
return "";
}
});
});
becomes:
var emailsPromise = new WinJS.Promise(function (complete, error, progress) {
// Open the picker for the user to select contacts
picker.pickMultipleContactsAsync().then(function (contacts) {
if (contacts.length > 0) {
// Get selected e-mails
contacts.forEach(function (contact) {
contact.emails.every(function (email) { output += email.value + ";"; });
});
complete(output);
} else {
complete("");
}
});
});