Validation of multiple empty field - javascript

I am trying to validate two fields in my form.
But it is displaying the error message only for one field.
Following is Javascript code:
function req() {
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
return false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
return false;
}
}
HTML code:
<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label>
<input name="txt_lnm" type="text" id="txt_lnm"/>\<label id="i1"></label>

If you need to get all errors tested, as "Disha" commented, you can not put a return statement in each if blocks.
var noError = true;
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
noError = false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
noError = false;
}
return noError;
That should work as you seems to want to.

Try This Code
JavaScript
`
function validate(){
var isValid = true;
if (document.reg_indi_form.txt_fnm.value=="") {
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
isValid = false;
}
if (document.reg_indi_form.txt_lnm.value=="") {
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
isValid = false;
}
return isValid;
}`

Related

Javascript Email Id Validation with checkbox

I am looking to do a Javascript email Id & checkbox validation. The validation is only working for the checkbox but not for the email id. how to correct it please?
codepen demo
function Validate()
{
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address");
return false;
}
return true;
}
function Validate(){
if(!validateForm()){
alert("Terms & Conditions!");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
// this function is called on form submit and checks the return values of both the email and checkbox function. if either of them are false, you will be alerted.
function MainFunction(){
if(!validateCheckBox() || !ValidateEmail() ){
return false;
}
alert("the form has been successfully submitted");
return true
}
// this function validates the email
function ValidateEmail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address");
return false;
}
return true;
}
// this function validates the checkbox
function validateCheckBox()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
alert("Terms & Conditions!");
return false;
}
//you had two of the same named function before. also you were only checking the return of one of the functions. Above checks the return values of both of the functions. Hope this helps
<form name="myform" id="form_id" method="post" onsubmit="return MainFunction();">
<input type="text" name="email" class="subscribe_email_nf" placeholder="Enter Your Email Id..."> <br />
<input type="checkbox" name="option1" value="1">Accept Terms & Conditions<br />
<input type="submit" value="Submit Form">
</form>

I have a problem with form validation in JS DOM

When i click a field and pass another, span tag is getting red color. Then i press the submit button it is showing alert message. But when i turn to red span and fill in the field and press submit button it is showing success even if other fields are blank.
const regForm = document.getElementById('regForm');
var validObjects = document.querySelectorAll('[customValidate]');
validObjects.forEach(function(element) {
element.addEventListener('blur', function() {
var emoji = element.previousElementSibling;
var label = emoji.previousElementSibling;
if (!element.value) {
emoji.className = "far fa-frown float-right text-danger";
var span = document.createElement("span");
span.innerHTML = " * Required";
span.style.color = "red";
if (!label.getElementsByTagName("span")[0])
label.appendChild(span);
isValid = false;
} else {
emoji.className = "far fa-smile float-right text-success";
var span = label.getElementsByTagName("span")[0];
if (span)
label.removeChild(span);
isValid = true;
}
});
});
regForm.addEventListener('submit', function(event) {
event.preventDefault();
var isValid = true;
validObjects.forEach(function(element) {
isValid = element.value ? true : false;
})
if (!isValid) {
alert("empty!");
} else {
alert("success!");
}
});
JSFiddle :https://jsfiddle.net/roop06/cjmdabrf/
because isValid is only going to be equal to the last item in the forEach
validObjects.forEach(function(element) {
isValid = element.value ? true : false; // replaces false with true on last iteration
})
If you want to use a forEach you would want to code it like this so it does not overwrite isValid. It uses its previous state.
var isValid = true;
validObjects.forEach(function(element) {
isValid = element.value ? isValid : false;
})
But if you are not doing anything else in the forEach loop, there is a better option. That option is to use every which will exit when it gets to false.
var isValid = validObjects.every(function (element) {
return element.value.length
})
var form = document.querySelector('form');
var validObjects = Array.from(document.querySelectorAll('[customValidate]'));
form.addEventListener("submit", function (e) {
var isValid = validObjects.every(function (element) {
return element.value.length
})
return isValid
})
<form>
<input customValidate>
<input customValidate>
<input customValidate>
<button>submit</button>
</form>
Or you can just use the built in HTML5 validation using required and let the browser do it for you.
<form>
<input customValidate required>
<input customValidate required>
<input customValidate required>
<button>submit</button>
</form>
Try this
JSFiddle
validObjects.forEach(function(element) {
if(!(element.value)){
isValid = false;
}
})
The problem you have is that if the last field is valid then the isValid flag will always be true. One way to get around this is to stop setting the flag once you have determined that there is an invalid field:
validObjects.forEach(function (element) {
if (isValid) {
isValid = element.value ? true : false;
}
});

I want to make a registration form but the script wont work the way i want

To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)

Validate textarea input for alphanumeric value

I want to validate textarea which is an Address field, it must contains both of letters and numbers, at least 1 number .
for example : "Laksda Adisucipto street, no 22A."
but when i just type : "Laksda Adisucipto street" (without number) it can show alert "you must enter at least 1 number"
i'm using Twitter Bootstrap and Validator.js
here's my code
HTML :
<div class="form-group col-md-12">
<label for="address" class="control-label"><span>*</span> <?php echo $this->lang->line('address');?></label>
<textarea class="form-control" id="address" rows="5" required name="address" data-error="Address is required"></textarea>
<span class="help-block with-errors"></span>
</div>
JS :
<script>
$('#address').change(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(($('#').value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
} );
Try this
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
you can check it here: http://jsfiddle.net/oa6eewck/
$('#address').blur(function()
{
var letterNumber = /^[0-9a-zA-Z]+$/;
if(this.value.match(letterNumber))
{
return true;
}
else
{
alert("message");
return false;
}
});
This function will allow only characters and numbers,it will be good for a input text field but since you are having text area "spaces" and "commas" and "periods" are expected right.
So better follow the expression follows :
$('#address').blur(function()
{
var hasNumber = this.value.match(/^[a-zA-Z0-9\s .,]+$/);
if ( hasNumber) {
return true;
} else {
alert("message");
return false;
}
});
$('#address').on('change', function () {
var hasNumber = this.value.match(/\d/);
var isAlfa = this.value.match(/^[0-9a-zA-Z]+$/);
if ( hasNumber && isAlfa ) {
return true;
} else {
alert("message");
return false;
}
});
FIDDLE
adeneo's solution is right. but I think isAlfa should have following value
var isAlfa = this.value.match(/^[A-Za-z\d(-.,) ]+/);

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

Categories