Variable scope inside function Javascript - javascript

I am trying to validate form but whenever I click submit button it says:
ReferenceError: check_text is not defined
even though variable is present in local scope.
<form class="input-text-box" method="post" action="">
<input type="text" id="uname" name="uname" placeholder="First Name" autocomplete="off" required>
<input type="text" id="ulastname" name="ulastname" placeholder="Last Name" autocomplete="off" required>
<input type="text" id="uuname" name="uuname" placeholder="Username" autocomplete="off" required>
<input type="text" id="contact" name="contact" placeholder="Contact" autocomplete="off" required>
<input type="email" id="email" name="uemail" placeholder="Email Address" autocomplete="off" required>
<input type="password" id="pass-1" name="upass1" placeholder="Password" autocomplete="off" required>
<input type="password" id="pass-2" name="upass2" placeholder="Confirm Password" autocomplete="off"required>
<input type="submit" value="Sign Up" id="submit-btn" onclick="validate()">
<p class="term-cond">By joining, you agree to our Terms of Service </p>
<p class="term-cond" style="margin:40px 0 0 65px;">Already a member? Sign In </p>
</form>
Below is the Javascript code which is intended to validate the values:
var msg="";
var DOMstring = {
firstName:'uname',
lastName:'ulastname',
userName:'uuname',
contact:'contact',
email:'email',
pass1:'pass-1',
pass2:'pass-2',
submit:'submit-btn'
}
function validate(){
var status = false;
var firstName = document.getElementById(DOMstring.firstName).value;
status = checkText(firstName,'First Name');
var lastName = document.getElementById(DOMstring.lastName).value;
status = checkText(lastName,'Last Name');
var userName = document.getElementById(DOMstring.userName).value;
status=checkText(userName,'Username');
var contact = document.getElementById(DOMstring.contact).value;
status = checkNumber(contact);
var pass1 = document.getElementById(DOMstring.pass1).value;
status = checkPass(pass1);
var pass2 = document.getElementById(DOMstring.pass2).value;
status = comparePass(pass1,pass2);
if(status == true){
alert("successfully created an account");
return true;
}else{
alert("Please consider the following error messages<br>"+msg);
return false;
}
}
function checkText(DOMname,name){
var ckeck_text = /^[A-Za-z]$/;
if(!check_text.test(DOMname)){
msg += name + ' cannot contain numbers or special character.<br>';
return false;
}
return true;
}
function checkNumber(DOMnumber){
var check_number = /^[0-9]{10}$/;
if(!check_number.test(DOMnumber)){
msg += 'Number contains 10 digit only<br>';
return false;
}
return true;
}
function checkPass(DOMpass1){
var check_pass = /^(?=.*[\d])(?=.*[!##$%^&*])[\w!##$%^&*]{8,16}$/;
if(!check_pass.test(DOMpass1)){
msg += 'Password field should contain alphanumeric values and special character<br> and should be in range from 8 to 16<br>';
return false;
}
return true;
}
function comparePass(DOMpass1,DOMpass2){
if(!DOMpass1 === DOMpass2){
msg += 'Both password does not match<br>';
return false;
}
return true;
}
I don't understand how there is no variable inside of same name if I had used let instead of var then this output is reasonable but with following method why it is not defined. If anything I am missing please help me to understand as I am completely new to Javascript.

You have a typo here var ckeck_text = /^[A-Za-z]$/;

Related

html javascript form no longer working since adding new input field

I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">

How can i make innerHtml writes error only once?

I have a problem, I made a form validation in javascript and after all validation checks I put innerHtml += "actually error message" and the problem is how many times I click the submit button it writes out the message. Someone can help me to solve this? Or make this more elegant or better logic. I'm a beginner.
function regvalidate() {
var errortable = document.getElementById('log');
var x = document.forms["regform"]["username"].value;
var y = document.forms["regform"]["email"].value;
var z = document.forms["regform"]["pass1"].value;
var b = document.forms["regform"]["pass2"].value;
if (x == "" || y == "" || z == "" || b == "") {
errortable.innerHTML = 'Cant be empty field';
return false;
}
var regexEmail = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("email");
if (regexEmail.test(email.value)) {} else {
errortable.innerHTML += 'Invaild email address';
return false;
}
password1 = regform.pass1.value;
password2 = regform.pass2.value;
if (password1 != password2) {
errortable.innerHTML += 'Two pass dosent match';
return false;
}
}
<div id="log"></div>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username">
<input type="email" id="email" class="form-control" placeholder="email" name="email">
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1">
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2">
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" onClick="return regvalidate()" name="register_btn">Register</button>
</form>
just remove the + before =like the following
errortable.innerHTML += 'Two pass dosent match';
or do it like
errortable.innerHTML = '';
errortable.innerHTML += 'Two pass dosent match';

How to determine whether a form is valid and display a popup window depdnding on whether is is valid or not?

I'm trying to create a form where the user fills out their details, the form currently doesn't send if one of the fields has no input in it because I have added in a "required" into each of the tags to create the field. I have written some JavaScript to open a popup if the form is valid but it isn't working, the form submits to my PHP database but the pop up window doesn't appear. Any thoughts? Here is my current JavaScript.
Code for the form fields -
label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..." required>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name..." required>
<label for="phonenumber">Phone Number</label>
<input type="text" id="phonenumber" name="phonenumber" placeholder="The best number to contact you on..." required>
Code to call the script -
<button onclick="myFunction()">Submit</button>
JavaScript validation
<script>
function validateForm() {
var x = document.forms["fname"].value;
var y = document.forms["lname"].value;
var p = document.forms["phonenumber"].value;
if ([x == "", y =="", p ==""]); {
alert("Name must be filled out");
return false;
}
}
function myFunction() {
if (x == "") {
return false;
}
else {
alert("Thank you for making an enquiry, a member of our team will be in contact with you soon.");
}
}
Try Code Below
<script>
function validateForm() {
var x = document.forms["Forms"]["fname"].value;
var y = document.forms["Forms"]["lname"].value;
var p = document.forms["Forms"]["phonenumber"].value;
if (x == "" && y =="" && p ==""); {
alert("Name must be filled out");
return false;
}
else
{
return true ;
}
}
<form name="Forms" onSubmit="return validateForm() "><input type="text" name="fname" /><input type="text" name="lname" /><input type="text" name="phonenumber" /></form>
or you can simply use required in every input

Make form validation via custom attributes

please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>

Failed to validate email address with regular expression

I would like to run my page to test out whether my validation works. However, it does not work with email address. I have added regular expression for email address. It doesn't validate fully.
I entered a#live without typing .com it able to accept it. I assume this is because i type input="email" Correct me wrong. Is it due to the wrong regular expression or maybe the way I placed my code?
javascript
function validate(){
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var emailReg = '/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/';
var re = /^[\w ]+$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(email=="")
{
alert('Please fill in email fields');
return false;
}
else if(fname=="")
{
alert('Please fill in first name fields');
return false;
}
else if(lname=="")
{
alert('Please fill in last name fields');
return false;
}
return true;
}
register.php
<form name="registrationForm" method="post" id="registrationForm" class="registrationForm" action="processRegister.php" onclick="validate">
<div class='input1'>
<span id="emailAddress-label" class="help"></span>
<input class="regemailaddr" id="emailAddress" name="emailAddress" type="email" placeholder="Email Address " value="" required>
</div>
<br>
<span id="fname-label" style="margin-bottom:" class="help"></span>
<input id="fname" name="fname" type="text" placeholder="First Name " class="fname" value="" required>
<span id="lname-label" class="help"></span> <input id="lname" name="lname" type="text" placeholder="Last Name " class="lname" value="<?php echo $user_profile["lname"]; ?>" required>
<br>
<button class="greybtn" type="submit" id="submitButton">Submit</button>
<button class="cancelbtn" type="button" id="cancelButton" onclick="window.location='#';return false;">Cancel</button>
</form>
You have defined a regular expression
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
but you do not test against it
var isEmail = emailReg.test(email);

Categories

Resources