Validation for text input in JavaScript - javascript

I am writing form with small js function and email regex. I want to make validation and display error when input is empty or string for email (id = "email") is not valid. I want as well to make possibility to remove error class from input after clicking the button, when requirement for input will be achieved. In this moment my function will not remove error class from not email input unless correct email will be implemented (regex), so even if another input is ok, i am not able to pass the validation for that input until email will be correct.
My code:
Validation();
function Validation() {
$('.my-button').click(function(){
$("input,textarea").each(function() {
var element = $(this);
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email = document.getElementById("email");
var notification = document.getElementById("notification");
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my_item').addClass('error');
notification.style.display = "block";
}
else if (!reg.test(email.value)) {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my_item').addClass('error');
email.focus;
return false;
}
else if (!element.val() == "") {
element.closest('.label-error').css('visibility', 'hidden');
element.closest('.my_item').removeClass('error');
notification.style.display = "none";
}
});
});
}
}
Edit: html code below:
<div class="write-to-us">
<div class="col-md-12 field">
<p>Write to us</p>
</div>
<div class="col-md-12 field">
<div class="my_item">
<label>Name</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your Name</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my_item">
<label>Surname</label>
<input type="text" id="email" name="email" class="my-text-input">
<div class="label-error">Write your email</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my_item">
<label">Question</label>
<textarea type="text" name="subject" class="my-text-input"></textarea>
</div>
</div>
<div>
<button class="my-button">Check it</button>
</div>
</div>
Does anyone has idea how to solve it? To remove error class from other inputs and leave error only on email (if only email is incorrect)?

The problem is you check if the "email" element is correct for every input or textarea element. If you put another condition to check if the current element in the loop is the "email" element it should work fine.
Something like this:
function Validation() {
$('.my-button').click(function(){
$("input,textarea").each(function() {
var element = $(this);
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var notification = document.getElementById("notification");
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my_item').addClass('error');
notification.style.display = "block";
}
else if (!element.val() == "") {
element.closest('.label-error').css('visibility', 'hidden');
element.closest('.my_item').removeClass('error');
notification.style.display = "none";
}
if (element.attr("id") === "email" && !reg.test(element.val())) {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my_item').addClass('error');
element.focus;
}
});
});
}
}
I did not test it, but the idea is there. If you provide your html code I'll test it out.

Related

What is the equivalent of "form-group has-error" in Boostrap 4?

I am trying to make form. When we send information with errors, then should be color red where we entered wrong data and color green where we entered the correct data.
My .js file:
function checkForm()
{
var error=false;
var contactName = document.getElementById("contactName");
var contactLastName = document.getElementById("contactLastName");
var contactEmail = document.getElementById("contactEmail");
var contactInfo = document.getElementById("contactInfo");
if (contactName.value == "")
{
document.getElementById('errorName').className='alert alertdanger';
error=true;
}
if (contactLastName.value == "")
{
document.getElementById('errorLastName').className='alert alertdanger';
error=true;
}
if(contactInfo.value == "")
{
document.getElementById('errorInfo').className='alert alertdanger';
error = true;
}
else
{
var info = contactInfo.value;
if(info.length >= 250)
{
document.getElementById('errorInfoLength').className='alert alertdanger';
error=true;
}
}
if(contactEmail.value == "")
{
document.getElementById('errorMail').className='alert alertdanger';
error=true;
}
else
{
var email = contactEmail.value;
var regex = /^[a-zA-Z0-9._-]+#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
if(regex.test(email)==false)
{
document.getElementById('errorMailCorrect').innerHTML='Bad format!';
document.getElementById('errorMailCorrect').className='alert alertdanger';
error=true;
}
}
if (!error)
return true;
else
{
return false;
}
}
Form:
<form action="index.html#kontakt" method="post" onsubmit="return checkForm();">
<fieldset>
<div class="form-group" id="error1">
<p id="errorName" class="d-none">Add name!</p>
<label for="contactName">ImiÄ™</label>
<input type="text" id="contactName"/>
</div>
<div class="form-group" id="error2">
<p id="errorLastName" class="d-none">Add last name!</p>
<label for="contactLastName">Nazwisko</label>
<input type="text" id="contactLastName"/>
</div>
<div class="form-group" id="error3">
<p id="errorMail" class="d-none">Add email!</p>
<p id="errorMailCorrect" class="d-none">Wrong email!</p>
<label for="contactEmail">Email</label>
<input type="text" id="contactEmail" />
</div>
<div class="form-group" id="error4">
<p id="errorInfo" class="d-none">Add info!</p>
<p id="errorInfoLength" class="d-none">Limit is 250 chars!</p>
<label for="contactInfo">Informacja</label>
<input type="text" id="contactInfo" />
</div>
<input type="submit" value="Submit" />
</fieldset>
</form>
In bootrap 3.4.1 I could simply add to my .js file:
document.getElementById("error1").className="form-group has-error";
What is the equivalent of "form-group has-error" in Boostrap 4?
Also another question. What do you need to do to make the fields on the form validate the details you have entered immediately? Not after we submitted them.
This is explained in the Bootstrap 4 documentation. You can:
Use the :valid and :invalid CSS pseudo-classes. They only work if the form has the class .was-validated.
Or use the .is-valid and is-invalid CSS classes.
Validating before submitting can be done using standard HTML attributes such as required, pattern, etc.. If that does not cover your requirements, you can do it yourself with JavaScript. But that is a whole other topic and it is probably best to use some library or framework for that.

Error message beside textbox onkeyup event

I have textboxes that I want to show the error prompt beside it onkeyup event, but with no luck, it doesn't work. I have this as my reference: I want to show error message beside my textbox rather than alert in onkeyup event
$(function() {
$("#name").next('span').hide();
$("#name").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (name == "") {
span.text("Please enter your name").show();
return;
}
span.text('').hide();
});
$("#age").next('span').hide();
$("#age").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (age == "") {
span.text("Please enter your age").show();
return;
}
span.text('').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<hr>
<span></span>
<input type="text" id="age" name="age" />
<span></span>
You are using wrong variable names to check the values of the name field and age field.
Also, the span for the name field is after the hr it should be right next to the input field.
Check the snippet below, see the comments added;
Notice the Regex .replace(/\s/g,'') for removing all whitespace in the if condition.
$(function() {
$("#name").next('span').hide();
$("#name").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (input.replace(/\s/g,'') == "") { // wrong variable, name is undefined, should be input, also the regex is for removing all whitespaces;
span.text("Please enter your name").show();
return;
}
span.text('').hide();
});
$("#age").next('span').hide();
$("#age").keyup(function() {
var input = $(this).val();
var span = $(this).next('span');
if (input.replace(/\s/g,'') == "") { // same here
span.text("Please enter your age").show();
return;
}
span.text('').hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<span></span> <!-- span should be here, before the hr line break -->
<hr>
<input type="text" id="age" name="age" />
<span></span>

form validation problems with jquery / javascript

This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>

javascript disable/enable submit button when password match

i have this html
> <div class="row">
> <div class="col-xs-6 col-sm-6 col-md-6">
> <div class="form-group">
> <input type="password" name="pass1" id="pass1" class="form-control input-lg" placeholder="Password"
> tabindex="3">
> </div>
> </div>
> <div class="col-xs-6 col-sm-6 col-md-6">
> <div class="form-group">
> <input type="password" name="pass2" id="pass2" onkeyup="checkPass(); return false;" class="form-control
> input-lg" placeholder="Confirm Password ">
> <span id="confirmMessage" class="confirmMessage"></span>
> </div>
>
> </div>
>
> </div>
>
> <div class="row">
> <input type="submit" id="login" value="Register">
> </div>
How can I do something like this:
When the password is empty the submit should be disabled (disabled="disabled").
When something is typed in the passsword to remove the disabled attribute.
If the password field becomes empty again(the text is deleted) the submit button should be disabled again.
When the password does not match,the submit button should be disable
I tried something like this:
<script type="text/javascript">
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
$("#submit").attr("disabled", "disabled");
}
}
</script>
the javascript display message if password match or does not match but my problem is when the password does not match the SUBMIT button still go ahead and submit.
You must be changing element property, not attribute:
$(document).ready(function() {
var isDisabled = false;
$('#toggler').click(function() {
isDisabled = !isDisabled;
$('#submit').prop('disabled', isDisabled);
});
$('form').submit(function(e) {
e.preventDefault();
alert('Submiting');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<button type="button" id="toggler">Disable/Enable</button>
<button type="submit" id="submit">Submit</button>
</form>
Use something similar:
if (pass1.value && pass2.value && pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
$("#submit").prop("disabled", false);
} else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
$("#submit").prop("disabled", true);
}
I added two length checks (if value is "" it is evaluated as false), and added the #prop() call to enable the button, when the two strings match.
Sorry since i can't comment i'll answer instead
If you have a form (i assume you do event though i can't see it), you can do it like this
$("#form").on('submit', function(e) {
e.preventDefault();
if(!$('#submit').prop('disabled')){
$(this).submit();
}
});
Basically i stop the submission first then check if the button is disabled before submitting the form.

Form validation: remove error after onkeydown in input

I am working on my first for validation, really basic.
If you leave the 'username' input blank it will turn the username input border red and also place an alert icon in the input.
I am trying to 'remove' what was added when the validation failed as soon as the user starts typing in the input that caused the error.
So the scenario is: The user leaves Username blank, clicks Submit and then the border of the Username input goes red and an error icon appears. They then go back and they add their username into the Username input after the first character they type into the Username box I want the red border and error icon to disappear.
However my attempts have failed
My Fiddle
JS
function contactForm() {
var theForm = document.forms.contact;
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
theForm.onsubmit = function() {
if (theForm.username.value === '') {
errorUsername.style.display = 'block';
usernameInput.className = 'form__input form__input--red rounded-4';
return false;
} else {
theForm.username.onkeydown = function() {
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
};
return true;
};
};
};
contactForm();
HTML
<form name="contact" action="#" novalidate>
<div class="input__holder">
<input id="username" name="username" type="text" class="form__input rounded-4" placeholder="Username">
<div id="username-error" class="input__error">!</div>
</div>
<div class="input__holder">
<input name="password" type="password" class="form__input rounded-4" placeholder="Password">
</div>
<div class="input__holder">
<input name="email" type="text" class="form__input rounded-4" placeholder="E-mail">
</div>
<button type="submit" id="" class="submit-button rounded-4">Submit</button>
</form>
CSS
Too long, in Fiddle :)
You can add something like this on javascript
document.onkeyup = function() {
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
if (usernameInput.value.length === 0) return;
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
}
Here the fiddle:
https://jsfiddle.net/12apmo5j/12/
I think this solves your problem :)

Categories

Resources