javascript:very simple validation does not working - javascript

I can't figure out why this is not working as i did everything correct.
This is a simple create a account form. I put validation code for some of the field like name, email and password. There are many other fields. but first i m trying this.
The like is here:
jsfiddle
and the code of HTML:
First Name
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname />
<input type="text" name="remail" id="remail" />
New Pasword
<input type="password" name="rpass" id="rpass" />
<input name="regis" type="submit" class="color2" id="id" value="Submit" />
The javascript code here:
function validateRegis() {
//regex for fname and lname
var fname = $("#fname").val();
var lname = $("#lname").val();
var patt_n = /[a-z]{2,20}/i;
//checking fname and lname for regex matching
var ftest = patt_n.test(fname);
var ltest = patt_n.test(lname);
var remail = $("#remail").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9\_\.\-]+[a-zA-Z0-9\_\-]+#[a-zA-Z0-9]+[a-zA-Z0-9\.\-]+[a-zA-Z0-9]+\.[a-z]{2,4}$/;
var test = filter.test(remail);
var rpass = $("#rpass").val();
var patt = /[a-z0-9~!##$%^&*()_\ ]/i;
var test2 = patt.test(rpass);
if (fname === "" || ftest === false) {
alert("Please provide first name!");
$("#fname").focus();
return false;
} else if (lname === "" || ltest === false) {
alert("Please provide Last name!");
$("#lname").focus();
return false;
} else if (remail === "" || test === false) {
//
alert("Please provide email in correct format!");
$("#remail").focus();
return false;
} else if (rpass === "" || rpass.length < 8 || test2 === false) {
alert("Please provide password!");
$("#rpass").focus();
return false;
} else if ((fname !== "") & (lname !== "") & (remail !== "") & (test === true) & (rpass >= 8) & test2 === true) {
return true;
}
}
It needs jquery to run the code.

The problem is the validateRegis function is not available in the global scope.
In the fiddle UI left side panel, 2nd select box select No Wrap in body, it works fine.
Demo: Fiddle
When you select onLoad there, all the scripts under the script frame is wrapped under a anonymous function, so your validateRegis method becomes a local member of that anonymous function. Thus that function will not be available when the function submit is called causing an Uncaught ReferenceError: validateRegis is not defined error being thrown.

Related

Checking if fields are empty in Javascript?

I am trying to check if specific fields are empty or not so I can Authenticate users using Firebase. However JavaScript seems to be skipping over multiple bits of code and constantly only showing the same message onscreen. Here is my code...
let user = document.getElementsByName('username');
let em2 = document.getElementsByName('mail2');
let rem = document.getElementsByName('repeatMail');
let pass2 = document.getElementsByName('password2');
let rpass = document.getElementsByName('repeatPassword');
if ((user === '') && (em2 === '')) {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((rem === '') && (pass2 === '')) {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if (rpass === '') {
alert('Please make sure all fields are filled in correctly. Thank you');
} else if ((em2 !== rem) && (pass2 !== rpass)) {
alert('Please make sure all repeat fields match their parents. Thank you');
} else {
checkUsername()
}
It will constantly just skip to the last else if statement and no matter what will always give me the error I setup even if the fields do match in HTML. I am probably just overlooking something but I have been struggling with this for a while now. Does anyone know a solution? By the way this code is inside a function but that but I've given that a unique name and all it is, is a simple...
function regSecurity() {
}
Beside the neede value property of the input elements, you need to check for emptyness and then to check if both wanted inputs are the same.
function checkUsername() {
console.log('checkUsername');
return false;
}
function check() {
let user = document.getElementById('username').value,
em2 = document.getElementById('mail2').value,
rem = document.getElementById('repeatMail').value,
pass2 = document.getElementById('password2').value,
rpass = document.getElementById('repeatPassword').value;
if (!user || !em2 || !rem || !pass2 || !rpass) {
alert('Please make sure all fields are filled in correctly. Thank you');
return false;
}
if (em2 !== rem || pass2 !== rpass) {
alert('Please make sure all repeat fields match their parents. Thank you');
return false;
}
return checkUsername();
}
<form onsubmit="return check()">
<input type="text" id="username" placeholder="username">
<input type="text" id="mail2" placeholder="mail2">
<input type="text" id="repeatMail" placeholder="repeatMail">
<input type="text" id="password2" placeholder="password2">
<input type="text" id="repeatPassword" placeholder="repeatPassword">
<input type="submit">
</form>

How can this Javascript code handle the if/else statements better, or possibly use switches?

First off, if this is against the rules, or frowned upon I'm very sorry and feel free to downvote/close. I'm desperately stuck.
I'm having trouble with an HTML page I wrote which is supposed to consist of inputs with certain requirements, adding div's to display error messages , and automatically update those error messages onblur. The assignment was made to test our javascript skills, and thus must be completely validated through javascript.
Here are a few of the guidelines...
validating the form for four separate things:
presence of required fields
equality of password fields
conformance to a password policy (one uppercase, one number, length > 7)
validity of the email address
When any one of these are violated, I should deactivate the form’s submit button so that it is not clickable and add a child "div" to the error-display containing an error message describing the situation.
The code seems correct to me, and works spontaneously, but i believe since javascript is looked at one line at a time it isn't displaying error messages correctly or even getting to certain parts of my code at all.
Here is my large chunk of javascript code, I am mainly looking for a way to break out of these if/else blocks that my code seems stuck in:
function formValidation() {
var form = document.getElementById('project-form');
var username = document.getElementById('username');
var name = document.getElementById('name');
var phone = document.getElementById('phone-number');
var email = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirmation = document.getElementById('password-confirmation');
var submit = document.getElementById('submit-btn');
var errorDisplay = document.getElementById('error-display');
var missingFieldBoolean = false;
var passwordMismatchBoolean = false;
var isUpper = false;
var isNumber = false;
var passwordLength = false;
var validEmail = false;
var createDiv = document.createElement("DIV");
var passwordConstraint, passwordConstraintError;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
//Checks all fields for empty values and updates error div
if (username.value.length == 0 || name.value.length == 0 || email.value.length == 0 || password.value.length == 0 || passwordConfirmation.value.length == 0) {
missingField = errorDisplay.appendChild(createDiv);
missingField.setAttribute("id", "required-field-error");
missingFieldError = document.getElementById('required-field-error');
missingFieldError.innerHTML = "Missing Fields: ";
if (username.value.length == 0) {
missingFieldError.innerHTML += "Username - ";
}
if (name.value.length == 0) {
missingFieldError.innerHTML += "Full Name - ";
}
if (email.value.length == 0) {
missingFieldError.innerHTML += "Email - ";
}
if (password.value.length == 0) {
missingFieldError.innerHTML += "Password - ";
}
if (passwordConfirmation.value.length == 0) {
missingFieldError.innerHTML += "Password Confirmation - ";
}
} else {
errorDisplay.removeChild(missingFieldError);
missingFieldBoolean = true;
}
//Checks password vs password confirmation to see if they match, else updates error div
if (password.value != passwordConfirmation.value) {
passwordMismatch = errorDisplay.appendChild(createDiv);
passwordMismatch.setAttribute("id", "password-mismatch-error");
passwordMismatchError = document.getElementById('password-mismatch-error');
passwordMismatchError.innerHTML = "The Password and Password Confirmation do not match. Please re-enter.";
} else {
errorDisplay.removeChild(passwordMismatchError);
passwordMismatchBoolean = true;
}
//for loop to iterate through password to check for required characters, else updates error div
for (var index = 0; index < password.value.length; index++) {
if (password.value.charAt(index) == password.value.charAt(index).toUpperCase) {
isUpper = true;
}
if ("0123456789".indexOf(password.value.charAt(index)) > -1) {
isNumber = true;
}
if (password.value.length > 7) {
passwordLength = true;
} else {
passwordConstraint = errorDisplay.appendChild(createDiv);
passwordConstraint.setAttribute("id", "password-constraint-error");
passwordConstraintError = document.getElementById('password-constraint-error');
passwordConstraintError.innerHTML = "The Password must be 8 characters long, with one uppercase letter and one number. ";
}
}
//checks if password constraints are met and removes div if true
if (isUpper && isNumber && passwordLength) {
errorDisplay.removeChild(passwordConstraintError);
}
//checks email, if invalid it adds error div, else it removes the div ***NOT WORKING***
if (!(mailformat.test(email.value))) {
invalidEmail = errorDisplay.appendChild(createDiv);
invalidEmail.setAttribute("id", "invalid-email-error");
invalidEmailError = document.getElementById('invalid-email-error');
invalidEmailError.innerHTML = "Please enter a valid email address.";
} else {
errorDisplay.removeChild(invalidEmailError);
validEmail = true;
}
//if all requirements are met and true, submit button becomes enabled ***NOT WORKING***
if (isUpper && isNumber && passwordLength && missingFieldBoolean && passwordMismatchBoolean && validEmail) {
submit.disabled = false;
}
}
<div id="error-display"></div>
<br>
<form id="project-form" action="/submit.php" method="get" onclick="formValidation()">
<label>Username:</label>
<input id="username" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Full Name:</label>
<input id="name" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Phone Number:</label>
<input id="phone-number" type="tel">
<br>
<label>Email:</label>
<input id="email" type="email" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Password:</label>
<input id="password" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<label>Confirm Password:</label>
<input id="password-confirmation" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<br>
<input id="submit-btn" type="submit" value="Submit" disabled>
</form>
Thanks a lot in advance, and again sorry if i'm breaking the rules.
I would put all the inputs into an object instead, that way you could automatically iterate over the object.
const fieldValues = [
'username',
'name',
'phone-number',
'email',
'password',
'password-confirmation',
]
.reduce((fieldsSoFar, fieldName) => {
fieldsSoFar[fieldName] = document.getElementById(fieldName).value;
return fieldsSoFar;
}, {});
const missingFieldsStr =
Object.entries(fieldValues)
.filter(([, fieldValue]) => fieldValue.length === 0)
.map(([fieldName]) => {
const words = fieldName.split(' ');
const upperWords = words.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
return upperWords;
})
.join(', ');
if (missingFieldsStr) {
// display it
}
// skipping some lines...
const hasUpper = /[A-Z]/.test(fieldValues.password);
const hasNumber = /[0-9]/.test(fieldValues.password);
And so on.
Don't implicitly create global variables - strongly consider using a linter.
Only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.

Javascript form validation not working for 2 input fields

I am trying to validate my form using javascript. I want that if a user leaves an input field empty then he will see an alert and the form will not submit data to php file. Unfortunatlly, the code below is not working for me. javascript is not executing on form submit.
javascript
<script>
function MyForm() {
var x =document.forms["myForm"]["name"].value;
if (x == null || x == "") {alert("Name must be filled out");
return false;
}
{ var y=document.forms["myForm"]["age"].value;
if (y == null || y == "") {
alert("age must be filled out");
return false;
}
}
form
<form name="myForm"action="game.php"onsubmit="return myForm()"method="post">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
Any help is greatly appriciated.
You've got a couple typos in your code. A good way to find them is to use the console in the developer tools of your browser (try pressing F12).
Change
{ var y=document.forms["myForm"]["age"].value;
to
var y=document.forms["myForm"]["age"].value; //removed the opening curly brace
and in your form change:
onsubmit="return myForm()"
to
onsubmit="return MyForm()"
you have to invoke myForm function first to make it work
function MyForm() {
var x =document.forms["myForm"]["name"].value;
if (x == null || x == "")
{alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["age"].value;
if (y == null || y == "") {
alert("age must be filled out");
return false;
}
}
MyForm(); // invoke it here
There are 2 typo issue in your javascript method. Try below method
function MyForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
var y=document.forms["myForm"]["age"].value;
if (y == null || y == "") {
alert("age must be filled out");
return false;
}
}

Validating a form in Javascript not working

I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}

Validation code issue

I'm trying to create a simple validation script which checks if text was entered or not in a textbox. I wrote the following code, which unfortunately does not print the alert.
<html>
<head>
<title> Js Page </title>
<script>
function validateName()
{
var FirstName=document.forms["myForm"]["firstname"].value;
if(FirstName==null || FirstName=="" )
{
alert("Please insert the corect First/Lastname");
return false;
}
}
</script>
</head>
<body>
<form name = "myForm" onsubmit = "return validateName()" method="post">
First name: <input type="text" name="firstname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
It is better to use id
<input type="text" name="firstname" id="firstnameId">
function validateName()
{
if(document.getElementById("firstnameId").value == ""){
alert("Please insert the corect First/Lastname");
return false;
} else
return true;
}
From firefox error console:
Timestamp: 6/29/2013 5:37:41 PM Error: SyntaxError: missing } after
function body Source File:
file:///C:/Users/developer/Desktop/adad.html Line: 13
You're missing } in function body.
function validateName()
{
var FirstName=document.forms["myForm"]["firstname"].value;
if(FirstName==null || FirstName=="" )
{
alert("Please insert the corect First/Lastname");
return false;
}
}
you are miising "}" at the in your jaavascript function
try to add developer tools of your browser it is advisable to use.
Maybe it would ignore the emptiness because of the space characters. You should use trim().
var FirstName = document.forms["myForm"]["firstname"].value.trim();
if(FirstName == ""){
}
is good for checking emptiness.
you can also use jQuery:
(give id="firstname" in your textox)
$(document).ready(function() {
$('#login').click(function() {
var username = $('#firstname').val();
if ($.trim(username).length == 0) {
alert('Please enter User name.');
return false;
e.preventDefault();
}
});
});
this is the complete validation for email
<script>
function validateForm()
{
var x=document.forms["register"]["email"].value;
var atpos=x.indexOf("#");
var space=x.indexOf(" ");
var dollar=x.indexOf("$");
var hash=x.indexOf("#");
var per=x.indexOf("%");
var or=x.indexOf("^");
var amber=x.indexOf("&");
var star=x.indexOf("*");
var plus=x.indexOf("+");
var minus=x.indexOf("-");
var coma=x.indexOf(",");
var dotpos=x.lastIndexOf(".");
var neg=x.indexOf("~");
var neq=x.indexOf("!");
var b1=x.indexOf(")");
var b2=x.indexOf("(");
var b3=x.indexOf(":");
var b5=x.indexOf("?");
var b6=x.indexOf(">");
var b7=x.indexOf("<");
var b8=x.indexOf("}");
var b9=x.indexOf("{");
var b10=x.indexOf("|");
if (x==null || x=="")
{
alert("Email is mandatory");
return false;
}
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length || space>0 || dollar>0 || hash>0 || per>0 || or>0 || amber>0 || star>0 || plus>0 || minus>0 || coma>0 || neg>0 || neq>0 || b1>0 || b2>0 || b3>0 || b5>0 || b6>0 || b7>0 || b8>0 || b9>0 || b10>0)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<form name="register" onsubmit="return validateForm()" action='http:\\www.google.com' method='get'>
<font face="Times New Roaman">Email Address*</font></td><td><input type='text' name='email' value='example#domain.com' onblur="if (this.value == '') {this.value = 'example#domain.com';}"
onfocus="if (this.value == 'example#domain.com') {this.value = '';}">
<input type='submit' value='submit'>
</form>

Categories

Resources