How do I validate in case when where I have 4 fields and only 1 is required. I want the pop up alert message to come up only when all 4 of the fields are left blank when user tries to save form.
My html looks like this.
<input id="txtWorkPhone" name="txtWorkPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput"/>
<input id="txtHomePhone" name="txtHomePhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" required="required" />
<input id="txtEmail" name="txtEmail" maxlength="260" required="required" class="k-textbox standardInput" style="width: 54%;" />
<input id="txtCellPhone" name="txtCellPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
As you can see I marked all the fields are required.. So how should i go about the validation of these fields ?
You can do custom validation as I did. Please check.
$('#submit').click(function () {
var allFilled = true;
$(':input:not(:button)').each(function(index, element) {
if (element.value === '') {
allFilled = false;
}
});
alert(allFilled);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm" id="myForm">
<input id="txtWorkPhone" name="txtWorkPhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput"/>
<input id="txtHomePhone" name="txtHomePhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
<input id="txtEmail" name="txtEmail" maxlength="260" class="k-textbox standardInput" style="width: 54%;" />
<input id="txtCellPhone" name="txtCellPhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
<input type="button" id="submit" name="submit" value="Submit">
</form>
On a button click you can simply do this:-
$('button').on('click', function () {
var isEmpty = $('input[required]').filter(function () {
return $.trim(this.value).length > 0
}).length == 0;
if (isEmpty) {
alert('Empty');
} else {
alert('Valid');
}
});
Now here:-
$('input[required]').filter(function () {
return $.trim(this.value).length > 0
})
Checks for all the inputs having some data entered in it. Next if that .length == 0; that means all of the inputs are empty. If that value is greater than 0 that means atleast one of the inputs out of 4 have some value.
Hope it helps!
<form onsubmit="myFunction()">
<input id="txtWorkPhone" name="txtWorkPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput"/>
<input id="txtHomePhone" name="txtHomePhone" data-role="maskedtextbox" data-mask="(999)-000-0000" class="k-textbox phoneInput" required="required" />
<input id="txtEmail" name="txtEmail" maxlength="260" required="required" class="k-textbox standardInput" style="width: 54%;" />
<input id="txtCellPhone" name="txtCellPhone" data-role="maskedtextbox" required="required" data-mask="(999)-000-0000" class="k-textbox phoneInput" />
</form>
<script>
function myfunction()
{
if($(#txtWorkPhone).value() === '' && if($(#textHomePhone).value() === '' && if($(#txtEmail).value() === '' && if($(#txtCellPhone).value() === '')
{
// do whatever.
}
}
</script>
Related
I want to create a sign-up form. I have 6 inputs: First Name, Last Name, E-mail, Password, Password confirmation and a checkbox for user agreement. If inputs have class="valid", value is valid, otherwise invalid. I put all the classes a default class="invalid". I want to disable my submit button until all input fields have class="valid". According to my research, I saw that the button should be disabled first using the window.onload eventlistener, but I still couldn't figure out how to do it.
This is the basic form:
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
I am controlling checkbox validation with an eventlistener:
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
})
And for the rest, i am checking with regexs:
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value])
})
})
Something like this might come in handy.
var form = document.querySelector('.signup__form'), is_valid = false, fields, button;
form.addEventListener('change', function(){
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if( fields[i].classList.contains('invalid') )
{
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled'): button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Since you don't have all of your code, I'm adding a second example myself so that I can fully test the validation part.
But you just need to copy the above JavaScript code and set the button to disabled="disabled"in the first place.
var form = document.querySelector('.signup__form'),
is_valid = false,
fields, button;
form.addEventListener('change', function() {
fields = form.querySelectorAll('input');
button = form.querySelector('button');
for (var i = fields.length - 1; i >= 0; i--) {
if (fields[i].value.length) {
fields[i].classList.remove('invalid');
} else {
fields[i].classList.add('invalid');
}
if (fields[i].classList.contains('invalid')) {
is_valid = false;
break;
}
is_valid = true;
}
is_valid ? button.removeAttribute('disabled') : button.setAttribute('disabled', 'disabled');
});
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name" /> <br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /><br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /><br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement<br>
<button type="submit" disabled>Sign Up</button>
</form>
Note: This example does not follow because it does not validate the Checkbox.
#Enes, 1. kod parçacığındaki JavaScript kodunu kopyalarsan çalışacaktır. 2. Kodu test edebilmen için ekledim. Bir değer girilmişse onu doğru "valid" kabul eder.
I would try to the native use of HTML properties (pattern & required) and CSS instead of giving in to javascript. Just give it a go, and see how it feels like. Do note that I excluded a pattern on your email input.
The only thing I would use javascript for is to check if the password fields are the same, but I would do that by injecting the password of the first password input into the confirming password input's pattern attribute, replacing ^[\w#-]{8,20}$.
The pink background is just there to show-case the validation rules.
By the way, you got the wrong formatting on some of the HTML tags. You don't need an ending slash on input and you should type <br/>, not </br>.
input:invalid {
background-color: pink;
}
form:invalid button[type="submit"] {
opacity: 0.5;
}
<form class="signup__form" action="/">
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Name"> <br/>
<input type="text" required pattern="^[a-zA-Z0-9]{3,24}$" placeholder="Last Name"><br/>
<input type="email" required placeholder="E-mail"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password Confirm"><br/>
<input type="checkbox" required>User Agreement<br/>
<button type="submit" >Sign Up</button>
</form>
you can use required="required", then the submit won't be called before the field has value.
A solution which tests the number of invalid classes:
var checkbox = document.querySelector("input[type=checkbox]");
var inputs = document.querySelectorAll("input:not([type='checkbox'])");
var but = document.querySelector("button[type=submit]");
but.disabled= true;
checkbox.addEventListener('click', (e) => {
if (e.target.checked) {
checkbox.classList.remove('invalid');
checkbox.classList.add('valid');
} else {
checkbox.classList.remove('valid');
checkbox.classList.add('invalid');
}
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
// Regex values
const regexs = {
fname: /^[a-zA-Z0-9]{3,24}$/,
lname: /^[a-zA-Z0-9]{3,24}$/,
email: /^([a-z\d\.-]+)#([a-z\d-]+)\.([a-z]{2,8})$/,
password: /^[\w#-]{8,20}$/
};
// Regex Validation
const validation = (input, regex) => {
if (regex.test(input.value)) {
input.classList.remove('invalid');
input.classList.add('valid');
} else {
input.classList.remove('valid');
input.classList.add('invalid');
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', (e) => {
validation(e.target,regexs[e.target.attributes.name.value]);
but.disabled = !document.querySelectorAll("input.invalid").length == 0;
})
})
<form class="signup__form" action="/">
<input class="invalid" type="text" name="fname" placeholder="name"/> </br>
<input class="invalid" type="text" name='lname' placeholder="Last Name" /></br>
<input class="invalid" type="email" name='email' placeholder="E-mail" /></br>
<input class="invalid" type="password" name="password" placeholder="Password" />
<input class="invalid" type="password" name="password" placeholder="Password Confirm" />
<input class="invalid" type="checkbox" /> User Agreement</br>
<button type="submit" >Sign Up</button>
</form>
We will use couple of properties to validate the form which are required, pattern, disabled and also we will use CSS properties to control the form validation
input:invalid {
background-color: red;
}
form:invalid input[type="submit"] {
opacity: 0.5;
cursor: not-allowed;
}
<form class="login__form" action="/">
<input type="email" required placeholder="E-mail"><br/><br/>
<input type="password" required pattern="^[\w#-]{8,20}$" placeholder="Password"><br/><br/>
<input type="submit" >
</form>
I have this form that the functionality is when all the required fields are completed to enable the submit button.
It was working until i added more interaction for a map gallery.
What could be wrong?
Im open to any suggestion or advice.
Im pretty new
Html
<h1>Contact me</h1>
<form action="" id="ContactForm" onsubmit="sConsole(event)">
<fieldset>
<p><label for="fullname">First Name:</label></p>
<input type="text" id="fullname" name="fullname" required />
<p><label for="lastname">Last Name:</label></p>
<input type="text" id="lastname" name="lastname" >
<p><label for="email">Email:</label></p>
<input type="email"id="email" email="email" required />
<p>Comment</p>
<label>
<textarea name="comments" id="comments" cols="30" rows="30" placeholder="Insert your comments here..." required ></textarea>
</label>
<p>Date of birth</p>
<label for="mydate">Pick a date:</label>
<input type="date" id="date" required />
<input type="submit" id="SubmitButton" disabled = "disabled" value="submit" onClick="sConsole()">
</fieldset>
Javascript
ContactForm.addEventListener("input" , () => {
if (fullname.value.length > 0 &&
lastname.value.length > 0 &&
email.value.length > 0 &&
comments.value.length > 0 &&
date.value.length > 0) {
SubmitButton.removeAttribute("disabled");
} else {
SubmitButton.setAttribute("disabled","disabled");
}
});
The new things that i added
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
const mapGallery = document.querySelectorAll(".maps-gallery");
let currentlySelected = 0;
prevBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected--;
mapGallery[currentlySelected].classList.add("active");
nextBtn.disabled = false
if (currentlySelected === 0){
prevBtn.disabled = true;
}
});
nextBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected++;
mapGallery[currentlySelected].classList.add("active");
prevBtn.disabled = false
if (mapGallery.length === currentlySelected +1 ){
nextBtn.disabled = true;
}
});
You need to use
document.getElementById("ContactForm").addEventListener
in the code. In this case, JavaScript needs to know the ID of the element to access.
Let say I have two input.
When I key-in value in input1 for example 0.4 and meets the requirement then the input2 will remove the readonly attribute. Meanwhile if I input value in input1 is 0.3 then the input2 attribute will become readonly again.
It doesnt work. Maybe i missed out anything here
$(".input1").keydown(function() {
var dInput = $(this).val();
if (dInput >= 0.4 && dInput <= 0.6) {
$(".input2").attr('readonly', true);
} else {
$(".input2").removeAttr("readonly");
}
});
function isNumberKey(e) { // stub
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />
<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />
1: Use keyup function, as the value fills up in a field later and you are trying to capture at keydown
2: I have switched the if and else block statements as per your description. Your original code contradicts what you are saying here.
$(".input1").keyup(function() {
var dInput = $(this).val();
if(dInput >= 0.4 && dInput <= 0.6)
{
$(".input2").removeAttr("readonly");
}
else
{
$(".input2").attr('readonly',true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" o id="input1" name="input1" value="" />
<input type="text" class="input2" id="input2" name="input2" value="" readonly />
You are setting the attribute in the wrong condition. I also prefer input event instead of keydown here:
$(".input1").on('input', function() {
var dInput = $(this).val();
if(dInput >= 0.4 && dInput <= 0.6){
$(".input2").removeAttr("readonly");
}
else{
$(".input2").attr('readonly', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" id="input1" name="input1" value="" />
<input type="text" class="input2" id="input2" name="input2" value="" readonly />
use keyup
function isNumberKey(e){
}
$(".input1").keyup(function() {
var dInput = $(this).val();
dInput = parseFloat(dInput);
console.log(dInput);
if(dInput >= 0.4 && dInput <= 0.6)
{
$(".input2").attr('readonly',true);
}
else
{
$(".input2").removeAttr("readonly");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />
<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />
I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}
When a textbox is created, default, gray text (#888) is given a displayed. When it is given focus, the value should disappear and start showing the typed value. I've written the code for this problem and it is as follows:
<html>
<script type="text/javascript">
function Focus(i) {
if (i.value == i.defaultValue) {
i.value = "";
i.style.color = "#000";
}
}
function Blur(i) {
if (i.value == "") {
i.value = i.defaultValue;
i.style.color = "#888";
}
}
</script>
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="Focus(this)" onblur="Blur(this)" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;"
value="lastname" onfocus="Focus(this)" onblur="Blur(this)" />
</body>
</html>
But, here whenever the textbox is focused, the value is disappearing. What should I do in order to correct this? Even though the text box is under focus, the value should not disappear and the value should disappear only when I start typing in it. I'm a new user so I can't post screenshots.
what you want is called placeholder.
use it like this:
<input type="text" name="enterfirstname" placeholder="First Name" />
<input type="text" name="enterlastname" placeholder="Last Name" />
Try with
<html>
<head>
<script type="text/javascript">
function Focus(i) {
if (i.value == i.defaultValue) {
i.value = "";
i.style.color = "#000";
}
}
function Blur(i) {
if (i.value == "") {
i.value = i.defaultValue;
i.style.color = "#888";
}
}
</script>
</head>
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;"
value="First Name" onfocus="Focus(this)" onblur="Blur(this)" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;"
value="lastname" onfocus="Focus(this)" onblur="Blur(this)" />
</body>
</html>
Note:script tags not inside body/head elements create invalid HTML
Try using "onkeydown" as following...
function Focus(cntrl,value)
{
if (cntrl.value == value)
{
cntrl.value = '';
cntrl.style.color = '#000';
}
}
function Blur(cntrl,value)
{
if (cntrl.value == '')
{
cntrl.style.color = 'gray';
cntrl.value = value;
}
}
<body>
<input type="text" name="enter firstname" title="First Name" style="color:#888;" value="First Name" onkeydown="Focus(this,'First Name')" onblur="Blur(this,'First Name')" />
<input type="text" name="enterlastname" title="Last Name" style="color:#888;" value="lastname" onkeydown="Focus(this,'lastname')" onblur="Blur(this,'lastname')" />
</body>