How to solve javascript redirection problem? - javascript

I am trying to do client-side validation using javascript and all the things are working properly, only it doesn't redirect to another page -> redirect.html
After clicking on the alert pop-up it again loads the index.html.
document.getElementById('sub-btn').addEventListener('click', function() {
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Sign Up</title>
</head>
<body>
<div class="main">
<div class="form-box">
<form class="input">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
</div>
</div>
</body>
<script src="script.js" type="text/javascript"></script>
</html>

Referring the link button type submit/button
document.getElementById('sub-btn').addEventListener('click', function() {
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8"></meta>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Sign Up</title>
</head>
<body>
<div class="main">
<div class="form-box">
<form class="input">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="button">SIGN UP</button>
</form>
</div>
</div>
</body>
<script src="script.js" type="text/javascript"></script>
</html>

you need to add event preventdefault I think

document.getElementById('sub-btn').addEventListener('click', function(e) {
e.preventDefault()
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
}else if (lastName.length === 0) {
alert('Enter the last name!');
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
}else if (phoneNum.length > 10) {
alert('Check phone number!');
}else if (emailID.length === 0) {
alert('Enter the email ID !');
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
}else {
alert('Redirecting to another page....');
window.location = 'redirect.html';
} });

form already has a built in redirect functionality by using the attribute action which also provides the benefit of actually posting the data to the desired link, if required.
Furthermore form has an event onsubmit which gets executed before submitting the form and can be cancelled by returning false.
Since all the mentioned requirements for your code are already given by the default behaviour of form, there is less reason not to use it.
Here is what you would need to change:
Instead of defining a click event, you define a standalone validation
function (=myValidator()), which returns true once all criterias are fulfilled and
false until. This better good practise anyway, since you can call it
independent of click events.
Setting the actionof the form to the desired URL (=redirect.html)
Forward the return of myValidator() to the onsubmit event on the form
function myValidator(){
//REM: returns true once valid, false until.
var tReturn = true;
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
tReturn = false
}else if (lastName.length === 0) {
alert('Enter the last name!');
tReturn = false
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
tReturn = false
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
tReturn = false
}else if (phoneNum.length > 10) {
alert('Check phone number!');
tReturn = false
}else if (emailID.length === 0) {
alert('Enter the email ID !');
tReturn = false
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
tReturn = false
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
tReturn = false
};
return tReturn
}
<!--REM: It is better practise to assign those events using javascript - I merely leave it here to point put the event/difference -->
<form class="input" action="redirect.html" onsubmit="return myValidator()">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
Also note that empty inputs can nowadays be prevented by using the attribute required as well as other nice form-features and be styled accordingly using pseudo-css-classes.
<form class="input" action="redirect.html">
<input class="input-field" id="fname" placeholder="First Name" type="text" required>
<input class="input-field" id="lname" placeholder="Last Name" type="text" required>
<input class="input-field" id="dob" placeholder="Date of Birth" type="date" required>
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text" required>
<input class="input-field" id="email" placeholder="Email ID" type="email" required>
<input class="input-field" id="password" placeholder="Enter Password" type="password" required>
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password" required>
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>

Related

Javascript not verifying whether or not special characters are inputted

When writing for special characters in password, it does not pass through, only the empty field and 6 character limit are egistered. I checked a bunch of places but I still get no result no matter where I look. When the regex was not there the confirm password entries worked as well, so something is out of place
Javascript:
function VerifyAndConfirmPassword()
{
var pw = document.forms["form"]["passPass"].value;
var pwC = document.forms["form"]["passCPass"].value;
if(pw == "")
{
alert("Password field is required");
return false;
}
if(pw.length < 6)
{
alert("Password length must be atleast 6 characters");
return false
}
var validPass = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]$/
if(!pw.value.match(validPass))
{
alert("Password requires at least one capital and lowercase letter , one number, and one special character")
return false;
}
if(pwC == "")
{
alert("Confirm Password field is required");
return false;
}
if(pw != pwC)
{
alert("Passwords do not match");
return false;
}
else
{
return true;
}
}
function VerifyAndConfirmPassword()
{
var pw = document.forms["form"]["passPass"].value;
var pwC = document.forms["form"]["passCPass"].value;
if(pw == "")
{
alert("Password field is required");
return false;
}
if(pw.length < 6)
{
alert("Password length must be atleast 6 characters");
return false
}
var validPass = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]$/
if(!pw.value.match(validPass))
{
alert("Password requires at least one capital and lowercase letter , one number, and one special character")
return false;
}
if(pwC == "")
{
alert("Confirm Password field is required");
return false;
}
if(pw != pwC)
{
alert("Passwords do not match");
return false;
}
else
{
return true;
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content = "width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="Assignment4.css">
</head>
<body>
<form name="form" onsubmit="return FirstName() && LastName() && Address() && City() && PostalCode() && ProvinceValues() && Age() && VerifyAndConfirmPassword() && Email()" method="post" action="mailto:jjohn#JJohnsonRE.ca">
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="txtFirst" maxlength="100" placeholder="Your First Name"><br><br>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="txtLast"maxlength="100" placeholder="Your Last Name"><br><br>
<label for="address">Address:</label><br>
<input type="text" name="txtAdd" maxlength="100" placeholder="Address"><br><br>
<label for="city">City:</label><br>
<input type="text" name="txtCity" maxlength="100" placeholder="City"><br><br>
<label for="postalCode">Postal Code:</label><br>
<input type="text" name="txtPC" maxlength="100" placeholder="Postal Code"><br><br>
<label for="province">Province: (Must use initials)</label><br>
<input type="text" id="txtPro" maxlength="100" placeholder="Province"><br><br>
<label for="age">Age:</label><br>
<input type="number" name="numAge" maxlength="100" placeholder="Age"><br><br>
<label for="password">Password:</label><br>
<input type="password" name="passPass" id="passPass" maxlength="100" placeholder="Password"><br><br>
<span id="message"></span>
<label for="Cpassword">Confirm Password:</label><br>
<input type="password" id="passCPass" name="passCPass" maxlength="100" placeholder="Password"><br><br>
<span id="messageC"></span>
<span id="confirm"></span>
<label>Your Email:</label><br>
<input name="txtEmail" type="text" maxlength="100" placeholder="Email"><br><br>
<input type="submit" value="Register Now">
<input type="reset" value="Clear Form">
</form>
<script src="Assignment4.js"></script>
</body>
</html>
!pw.value.match(validPass)
pw is already the value of the input field (defined as document.forms["form"]["passPass"].value). Getting the value property of a String returns null, and thus you get the error. Just use simply:
!pw.match(validPass)
You should also be returning the result of VerifyAndConfirmPassword() on submit, not FirstName() && LastName() && Address() && City() && PostalCode() && ProvinceValues() && Age() && VerifyAndConfirmPassword() && Email().
Use:
function VerifyAndConfirmPassword() {
var pw = document.forms["form"]["passPass"].value;
var pwC = document.forms["form"]["passCPass"].value;
if (pw == "") {
alert("Password field is required");
return false;
}
if (pw.length < 6) {
alert("Password length must be atleast 6 characters");
return false
}
var validPass = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]$/
if (!pw.match(validPass)) {
alert("Password requires at least one capital and lowercase letter , one number, and one special character")
return false;
}
if (pwC == "") {
alert("Confirm Password field is required");
return false;
}
if (pw != pwC) {
alert("Passwords do not match");
return false;
} else {
return true;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="Assignment4.css">
</head>
<body>
<form name="form" onsubmit="return VerifyAndConfirmPassword()" method="post" action="mailto:jjohn#JJohnsonRE.ca">
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="txtFirst" maxlength="100" placeholder="Your First Name"><br><br>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="txtLast" maxlength="100" placeholder="Your Last Name"><br><br>
<label for="address">Address:</label><br>
<input type="text" name="txtAdd" maxlength="100" placeholder="Address"><br><br>
<label for="city">City:</label><br>
<input type="text" name="txtCity" maxlength="100" placeholder="City"><br><br>
<label for="postalCode">Postal Code:</label><br>
<input type="text" name="txtPC" maxlength="100" placeholder="Postal Code"><br><br>
<label for="province">Province: (Must use initials)</label><br>
<input type="text" id="txtPro" maxlength="100" placeholder="Province"><br><br>
<label for="age">Age:</label><br>
<input type="number" name="numAge" maxlength="100" placeholder="Age"><br><br>
<label for="password">Password:</label><br>
<input type="password" name="passPass" id="passPass" maxlength="100" placeholder="Password"><br><br>
<span id="message"></span>
<label for="Cpassword">Confirm Password:</label><br>
<input type="password" id="passCPass" name="passCPass" maxlength="100" placeholder="Password"><br><br>
<span id="messageC"></span>
<span id="confirm"></span>
<label>Your Email:</label><br>
<input name="txtEmail" type="text" maxlength="100" placeholder="Email"><br><br>
<input type="submit" value="Register Now">
<input type="reset" value="Clear Form">
</form>
<script src="Assignment4.js"></script>
</body>
</html>

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

Validating more than one field on a form

I have a registration form and I want to validate that the password and email fields by adding confirm fields for each. Both field must be validated before clicking on the submit button. Is there a way to validate both email and password fields on the same form. Below is what i have for my password fields which works great but i need help to validate the email section too on the same form. thanks in advance
<Form>
<input type="email" name="email" id="email" placeholder="Email" required />
<input type="email" name="confirm_email" id="confirm_email" placeholder="Confirm Email" required />
<input type="text" name="username" id="username" placeholder="Company name" required />
<input name="password" id="password" type="password" placeholder="Password" onkeyup='check();' />
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check();' />
<span id='message'></span>
</Form>
<script>
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'Password match confirmed';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'Please confirm your password.';
}
}</script>
You need to check for the attributes using getAttribute() on where which input is being typed in and then from their you can do the validation of your email first.
Also, to make sure that email is always getting confirmed first we need to set a global variable which is initially false but as soon the email is confirmed it becomes true and then you can move on to the password feilds.
If you directly goes towards the password the input you will see the message that please verify you email first.
Lastly, i have cleaned up your and is simplified the code as well by declaring the inputs as variable so that we can use them again in our code if needed. I have also added when input field must not be empty when doing the validation of fields.
Live Working Demo:
var emailConfirmed = false
var message = document.getElementById('message')
var email = document.getElementById('email')
var confEmail = document.getElementById('confirm_email')
var password = document.getElementById('password')
var confPassword = document.getElementById('confirm_password')
function check(e) {
if (e.getAttribute('id') == 'email' || e.getAttribute('id') == 'confirm_email') {
if (email.value != '' && confEmail.value != '' && email.value == confEmail.value) {
message.style.color = 'green';
message.innerHTML = 'Email match confirmed';
emailConfirmed = true
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your email.';
emailConfirmed = false
}
}
if (e.getAttribute('id') == 'password' || e.getAttribute('id') == 'confirm_password') {
if (emailConfirmed) {
if (password.value != '' && confPassword.value != '' && password.value == confPassword.value) {
message.style.color = 'green';
message.innerHTML = 'Password match confirmed';
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your password.';
}
} else {
message.style.color = 'red';
message.innerHTML = 'Please confirm your email first.'
}
}
}
input {
display: block;
}
<form>
<input type="email" name="email" id="email" placeholder="Email" onkeyup='check(this);' required />
<input type="email" name="confirm_email" id="confirm_email" placeholder="Confirm Email" onkeyup='check(this);' required />
<input name="password" id="password" type="password" placeholder="Password" onkeyup='check(this);' />
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm Password" onkeyup='check(this);' />
<br>
<span id='message'></span>
</form>

How to get this form validation script working

I have created a form and a form validation script that checks if all fields are filled in, the name and city fields contain only letters, the age and phone fields contain only numbers and if the entered email is a valid one. When used in the console, all of the statements work, but when I fill in every field, or fill in invalid values in the email field or phone number and age field, I still get an error message saying that the name and city field must contain only letters.
I have tried writing out every statement alone and also checking them one by one.
HTML & JS
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$(".btn.btn-primary.submit").click(function () {
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
})
});
</script>
When I leave all fields empty the warning is ok. But when I do anything else I only get the warning that I can only use letters in the fields Name and City.
All help is greatly appreciated for a beginner!
I think you are failing to reassign the variables outside of the onClick function. I have tested below code and it works for me, i admit it is probably not a perfect solution reassigning all the variables each time and perhaps you could place some in global scope such as the RegEx statements. I also removed the loop as i don't think you need to loop over everything 5 times to check.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
$(".btn.btn-primary.submit").click(function () {
let name_cityRegex = /^[a-zA-Z]+$/;
let emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
let age_phoneRegex = /^\d+$/;
let nameValue = $('#inputName').val();
let cityValue = $('#inputCity').val();
let ageValue = $('#inputAge').val();
let phoneValue = $('#inputPhone').val();
let nameResult = name_cityRegex.test(nameValue);
let cityResult = name_cityRegex.test(cityValue);
let ageResult = age_phoneRegex.test(ageValue);
let phoneResult = age_phoneRegex.test(phoneValue);
let mailValue = $('#InputEmail').val();
let mailResult = emailRegex.test(mailValue);
if (nameValue == '' || cityValue == '' || ageValue == '' || phoneValue == '' || mailValue == '') {
$('.alert.alert-danger').show();
}
else if (nameResult === false || cityResult === false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
// })
});
</script>
</body>
</html>
I don't really know why your tests gives you an error, but I think your $('.form-control').each is useless.
In this foreach you test all your fields for each field.
Maybe try without this foreach, just test all your fields when you click on the button by removing this bit of code :
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
})
I don't see any other problem.
You have a syntax error I corrected that check below code.
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" name="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" name="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" name="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="text" name="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="text" name="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit" onClick="validateForm()">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>

Field wise form validation

On submitting an empty form I'm receiving the respective errors but I want to remove the error (when they meet the requirement) as I proceed to the next input. Also can anyone give me a solution to do the same with the help of loops. Only JavaScript solution please.
Here's my JS and HTML code..
function validate() {
var letter = /[a-zA-Z]/;
var number = /[1-9]{1}[0-9]{2}/;
var mail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var valid = true;
var firstname = information.first.value;
var lastname = information.last.value;
var address = information.Add.value;
var email = information.Email.value;
var pass = information.Pass.value;
var re_pass = information.Repass.value;
var phone = information.mobile.value;
if (firstname === "" || !letter.test(firstname)) {
document.getElementById("fn").innerHTML = "*Enter your First Name*";
console.log("first");
valid = false;
} else {
document.getElementById("fn").innerHTML = "";
}
if (lastname === "" || !letter.test(lastname)) {
document.getElementById("ln").innerHTML = "*Enter your Last Name*";
console.log("last");
valid = false;
} else {
document.getElementById("ln").innerHTML = "";
}
if (email === "" || !mail.test(email)) {
document.getElementById("mail").innerHTML = "*Enter your Email*";
console.log("mail");
valid = false;
} else {
document.getElementById("mail").innerHTML = "";
}
if (pass === "" || !letter.test(Pass)) {
document.getElementById("pwd").innerHTML = "*Enter your Password*";
console.log("password");
valid = false;
} else {
document.getElementById("pwd").innerHTML = "";
}
if (re_pass === "" || re_pass != pass) {
document.getElementById("repass").innerHTML = "*Password didn't match*";
console.log("reenter");
valid = false;
} else {
document.getElementById("repass").innerHTML = "";
}
if (phone == "" || !number.test(phone)) {
document.getElementById("no").innerHTML = "*Enter your Phone number";
console.log("phone");
valid = false;
} else {
document.getElementById("no").innerHTML = "";
}
return valid;
}
<!DOCTYPE html>
<html>
<head>
<title>information</title>
<link rel="stylesheet" type="text/css" href="info.css">
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="form">
<form action="#" method="POST" onsubmit="return validate()" name="information">
<label>Firstname:</label>
<input type="text" name="firstname" placeholder="Enter your name" id="first" autofocus>
<span id="fn"></span><br><br>
<label>Lastname:</label>
<input type="text" name="lastname" placeholder="Enter last name" id="last">
<span id="ln"></span><br><br>
<label>Address:</label>
<input type="text" name="address" placeholder="Address" id="Add">
<span id="add"></span><br><br>
<label>Email:</label>
<input type="email" name="mail" placeholder="Email" id="Email">
<span id="mail"></span><br><br>
<label>Password:</label>
<input type="password" name="password" placeholder="Password" id="Pass">
<span id="pwd"></span><br><br>
<label>Retype Password:</label>
<input type="password" name="retype" placeholder="Retype password" id="Repass">
<span id="repass"></span><br><br>
<label>Phone:</label>
<input type="text" name="firstname" placeholder="XXXXXXXXXX" id="mobile" maxlength = "10">
<span id="no"></span><br><br>
<input type="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>
Perhaps this?
var letter = /[a-zA-Z]/;
var number = /[1-9]{1}[0-9]{2}/;
var mail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
function validate() {
var information = document.querySelector("#form>form");
var error = 0;
var firstname = information.first.value;
var lastname = information.last.value;
var address = information.Add.value;
var email = information.Email.value;
var pass = information.Pass.value;
var re_pass = information.Repass.value;
var phone = information.mobile.value;
error += firstname === "" || !letter.test(firstname)
document.getElementById("fn").innerHTML = error?"*Enter your First Name*":"";
error += lastname === "" || !letter.test(lastname)
document.getElementById("ln").innerHTML = error?"*Enter your Last Name*":"";
error += email === "" || !mail.test(email)
document.getElementById("mail").innerHTML = error?"*Enter your Email*":"";
error += pass === "" || !letter.test(Pass)
document.getElementById("pwd").innerHTML = error?"*Enter your Password*":"";
error += re_pass === "" || re_pass !== pass
document.getElementById("repass").innerHTML = error?"*Password didn't match*":"";
error += phone === "" || !number.test(phone)
document.getElementById("no").innerHTML = error ? "*Enter your Phone number":"";
return error>0?false:true;
}
document.querySelector("#form>form").oninput = validate;
document.querySelector("#form>form").onsubmit = validate;
<div id="form">
<form action="#" method="POST" name="information">
<label>Firstname:</label>
<input type="text" name="firstname" placeholder="Enter your name" id="first" autofocus>
<span id="fn"></span><br><br>
<label>Lastname:</label>
<input type="text" name="lastname" placeholder="Enter last name" id="last">
<span id="ln"></span><br><br>
<label>Address:</label>
<input type="text" name="address" placeholder="Address" id="Add">
<span id="add"></span><br><br>
<label>Email:</label>
<input type="email" name="mail" placeholder="Email" id="Email">
<span id="mail"></span><br><br>
<label>Password:</label>
<input type="password" name="password" placeholder="Password" id="Pass">
<span id="pwd"></span><br><br>
<label>Retype Password:</label>
<input type="password" name="retype" placeholder="Retype password" id="Repass">
<span id="repass"></span><br><br>
<label>Phone:</label>
<input type="text" name="firstname" placeholder="XXXXXXXXXX" id="mobile" maxlength="10">
<span id="no"></span><br><br>
<input type="submit" name="mysubmit" value="submit">
</form>
</div>

Categories