Other two fields are required if the third field is not empty - javascript

I have three textfields namely :
State Code
Country Code
Telephone number
The value of StateCode and Country code is set by default.
If the Telephone Number textfield is entered, I want the other two fields to be made mandatory.
If the Telephone Number is empty then it is not required. How can I do this ?

I create this fiddle:
html
<label id="lblStateCode">State Code</label>
<input type="text" id="stateCode" value="585" />
<label id="lblCountryCode">Country Code</label>
<input type="text" id="countryCode" value="552" />
<label id="lblPhone">Phone</label>
<input type="text" id="phone" />
js
$("#phone, #stateCode, #countryCode").on("blur",function(){
if($("#phone").val() != ""){
if($("#stateCode").val() == ""){
$("#lblStateCode").addClass("errorClass");
}
else{
$("#lblStateCode").removeClass("errorClass");
}
if($("#countryCode").val() == ""){
$("#lblCountryCode").addClass("errorClass");
}
else{
$("#lblCountryCode").removeClass("errorClass");
}
}
else{
$("#lblStateCode").removeClass("errorClass");
$("#lblCountryCode").removeClass("errorClass");
}
});
$(function(){
if($("#phone").val() != ""){
if($("#stateCode").val() == ""){
$("#lblStateCode").addClass("errorClass");
}
else{
$("#lblStateCode").removeClass("errorClass");
}
if($("#countryCode").val() == ""){
$("#lblCountryCode").addClass("errorClass");
}
else{
$("#lblCountryCode").removeClass("errorClass");
}
}
else{
$("#lblStateCode").removeClass("errorClass");
$("#lblCountryCode").removeClass("errorClass");
}
});
css
.errorClass{
color:red;
}
fiddle

u need to apply jquery validations:
$("#form").validate({
rules: {
State: { required: function () {
if ($('#Telephone').val() != '') return true;
else return false;
},
Country: { required: function () {
if ($('#Telephone').val() != '') return true;
else return false;
}
}
messages: {
State: { required: "error messge" },
Country: { required: "error messge" }
}
});

Related

check the empty field instantly in jquery

I have to check the fields of my form if they are empty and display an error message in front of each empty field, but I can not find how to check the fields of a form and display an error message they are empty with jQuery. I tried with keyup but it does not do it instantly. Do you know how to do it in jQuery?
$(function() {
$("#myButton").click(function() {
valid = true;
if ($("#name").val() == "") {
$("#name").next(".error-message").fadeIn().text("Please enter your name")
valid = false;
} else if (!$("#name").val().match(/^[a-z]+$/i)) {
$("#name").next(".error-message").fadeIn().text("Please enter a valid name")
valid = false;
} else {
$("#name").next(".error-message").fadeOut();
}
if ($("#firstName").val() == "") {
$("#firstName").next(".error-message").fadeIn().text("Please enter your first name")
valid = false;
} else if (!$("#firstName").val().match(/^[a-z]+$/i)) {
$("#firstName").next(".error-message").fadeIn().text("Please enter a valid first name")
valid = false;
} else {
$("#firstName").next(".error-message").fadeOut();
}
if ($("#phone").val() == "") {
$("#phone").next(".error-message").fadeIn().text("Please enter your phone")
valid = false;
} else if (!$("#phone").val().match(/^[0-9]+$/i)) {
$("#phone").next(".error-message").fadeIn().text("Please enter a valid phone")
valid = false;
} else {
$("#phone").next(".error-message").fadeOut();
}
return valid;
});
});
.error-message {
display: none;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="myForm">
<fieldset>
<legend>Contact us</legend>
<label>Your name:</label>
<input type="text" name="name" id="name">
<span class="error-message">error</span>
<br />
<label>Your First name:</label>
<input type="text" name="firstName" id="firstName">
<span class="error-message">error</span>
<br />
<label>Your phone:</label>
<input type="text" name="phone" id="phone">
<span class="error-message">error</span>
<br />
<input type="submit" value="Submit" id="myButton">
</fieldset>
</form>
check my input for example , u may use onkeyup (when delete content)
my function checks how strong password is and if it's not empty
function checkPasswd(el, but) {
let password = $(el).val();
const strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})");
if (strongRegex.test(password)) {
$(el).css({
'background-color': '#58bc62'
});
$(but).attr("disabled", false);
} else {
if (password == "") {
$(el).css({
'background-color': 'white'
});
$(but).attr("disabled", true);
} else {
$(el).css({
'background-color': '#e57777'
});
$(but).attr("disabled", true);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="password" id="password" placeholder="new password..." onkeyup="checkPasswd('#password', '.saveToDbButton')" class="add_user" required>
I succeeded
$("#name").focusout(function () {
if (!$(this).val()) {
$("#name").next(".error-message").fadeIn().text("Please enter your name");
name = false;
}
else if(!$("#name").val().match(/^[a-z]+$/i)){
$("#name").next(".error-message").fadeIn().text("Please enter a valid name");
name = false;
}
else{
$("#name").next(".error-message").fadeOut();
}
});
$("#firstName").focusout(function () {
if (!$(this).val()) {
$("#firstName").next(".error-message").fadeIn().text("Please enter your first name");
firstName = false;
}
else if(!$("#firstName").val().match(/^[a-z]+$/i)){
$("#firstName").next(".error-message").fadeIn().text("Please enter a valid first name");
firstName = false;
}
else{
$("#firstName").next(".error-message").fadeOut();
}
});
$("#phone").focusout(function () {
if (!$(this).val()) {
$("#phone").next(".error-message").fadeIn().text("Please enter your phone");
phone = false;
}
else if(!$("#phone").val().match(/^[0-9]{10}$/i)){
$("#phone").next(".error-message").fadeIn().text("Please enter your phone");
phone = false;
}
else{
$("#phone").next(".error-message").fadeOut();
}
});

Javascript multiple fields validating

First, I have to validate that id and password textboxes are not empty(That one's working). Then I have to validate on the same form that id on textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work). Any ideas on what's wrong with my code?
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID;
custID = document.getElementsByName("idtb").valueOf();
if (custID !== isNan) {
alert("Customer ID needs to be numeric");
return false;
}
if (custID < 3000) {
alert("ID must be above 3000");
return false;
}
if (custID > 3999) {
alert("ID must be below 3999");
return false;
}
}
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID = document.getElementById('idtb').value;
if (Number.isNaN(parseInt(custID))) {
alert("Customer ID needs to be numeric");
return false;
}
if (parseInt(custID) < 3000) {
alert("ID must be above 3000");
return false;
}
if (parseInt(custID) > 3999) {
alert("ID must be below 3999");
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form action="#" onsubmit="return validatefunctions()" method="post">
Customer ID: <input type="text" name="idtb" id="idtb"><br /><br />
Password: <input type="text" name="pwtb" id="pwtb"><br /><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work)
Why don't use input type number specifying the min and max attribute:
<form>
<input type="number" name="quantity" min="3000" max="3999" value="3000">
<input type="submit">
</form>

jQuery validation is not working in contact form

I want validation through jQuery. I have two fields name and email. email blank field validation is not working.
Here is my code,
<form>
Name : <input type="text" name="name" id="name"><br>
<span id="nameSpan"></span>
<br>
Email:<input type="email" name="email" id="email1"><br>
<span id="emailSpan"></span>
<br>
<input type="submit" id="submitBtn">
</form>
javascript
$(document).ready(function(){
var name = $("#name").val();
var email1 = $("#email1").val();
$("#submitBtn").on("click", function(){
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Please guide me where am I wrong. Thanks in advance
You are checking values of inputs only once while page load. We need to check them everytime so lets move this part into onclick function.
$(document).ready(function(){
$("#submitBtn").on("click", function(){
var name = $("#name").val();
var email1 = $("#email1").val();
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});

The below jsp file doesn't validate from radio button onwards

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Validation Form</title>
<script type="text/javascript">
function validate()
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var atposition=email_str.indexOf("#");
var dotposition=email_str.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address")
return false
}
if ((!document.getElementById("a").checked)&&(!document.getElementById("b").checked))
{
alert("no button is selected");
return false
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length)
return alert("No box is checked");
var group2 = document.getElementById.dd;
var index_opt = group2.options[group2.selectedIndex].value;
if(index_opt==Select)
{
alert("select course")
return false
}
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name="my_form" onsubmit="validate()">
<strong>Name:&nbsp&nbsp&nbsp</strong>
<input type=text name=name><br/>
<strong>Password:&nbsp&nbsp&nbsp</strong>
<input type=password name=pwd><br/>
<strong>Retype Password:&nbsp&nbsp&nbsp</strong>
<input type=password name=repwd><br/>
<strong>Age:&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=age><br/>
<strong>Phone No:&nbsp&nbsp&nbsp&nbsp</strong>
<input tupe= text name=ph><br/>
<strong>Email:&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=email><br/><br/>
<strong>Sex:&nbsp&nbsp&nbsp&nbsp</strong>
<input type= "radio" name="gender" id="a" value="Male">Male&nbsp&nbsp&nbsp&nbsp
<input type= "radio" name="gender" id="b" value="Female">Female&nbsp&nbsp&nbsp&nbsp<br/><br/><br/>
<strong>Hobby:</strong>
<input type="checkbox"name= "hobby" id="1" value="singning">Singning<br/>
<input type="checkbox"name= "hobby" id="2" value="reading">Reading<br/>
<input type="checkbox"name= "hobby" id="3" value="tv">TV<br/>
<br/>
<strong>Country</strong>
<select name="mymenu" id="dd">
<option value ="Select">Select</option>
<option value ="India">India</option>
<option value ="China">China</option>
<option value ="SriLanka">SriLanka</option>
</select>
<input type="submit" value=Submit>
<input type="reset" value=Reset><br/>
</form>
</body>
</html>
The code doesn't validate from the radio button on wards. but if i run the radio button code and the other validation codes after the radio button code it works and when compiled in a single form it doesn't works. the drop down menu validation doesn't works at all. please help me. Thanks in advance.
It's not a problem with your radio button check. In your code, you can use one variable like x, that's the problem. kindly refer below code :
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
That above code x variable doesn't declare and doesn't assign any where in your code. So that line error occurred and terminated.
You change this x to email_str, As per your code should be like below,
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email_str.length)
It's working fine.
First of all you should change your on submit Event like below
<form name="my_form" onsubmit="return validate(this.form)">
Here your complete Javascript
<script type="text/javascript">
function validate(form)
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var email = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
var gender=document.my_form.gender.value;
if((gender=="null")||(gender=="")){
alert("Please Select Gender");
return false;
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length){
alert("No box is checked");
return false;
}
var country=document.my_form.mymenu.value;
if(country=='Select'){
alert("You must Select your Country");
return false;
}
}
</script>

jQuery form validation issue

I'm not using any jQuery plugin to validate the form, just plain jQuery. My issue is that after it validates all the input elements, even if it shows the error message to the user, it will still submit the form without the user correcting the error.
To elaborate, my form has 3 input elements. with jQuery validation, if all the 3 elements are empty, and the user clicks on the Submit button, it will throw an error highlighting the first element. If the user does not correct the error, but clicks on the submit button again, it will highlight the second element [with the first input element still highlighted]. Likewise for the 3rd element. Now if the user without correcting the error (that is, the input elements are still highlighted) clicks on the submit button again, it will submit the form. Ideally, it should keep on highlighting the first input element till the user corrects his error and then validate the 2nd input element and so on. .and this is what I want to do.
jQuery code:
$(function() {
/*Form Validation*/
$("#name")
.focus(function() {
if ($(this).val() == "Your Name" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Name");
}
})
.keyup(function() {
$("#name").val($(this).val());
}),
$("#email")
.focus(function() {
if ($(this).val() == "Your Email" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Email");
}
})
.keyup(function() {
$("#email").val($(this).val());
}),
$("#msg")
.focus(function() {
if ($(this).val() == "Your Message" || $(this).val() == "You forgot to enter your message" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Message");
}
})
.keyup(function() {
$("#msg").val($(this).val());
})
});
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name") {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email") {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message") {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
. .html:
<form action="somepage.php" method="post" id="contactform">
<div class="container">
<div class="field">
<input type="text" tabindex="1" value="Your Name" name="name" id="name" /><br />
</div>
<div class="field">
<input type="text" tabindex="2" value="Your Email" name="name" id="email" /><br />
</div>
<div class="field">
<textarea tabindex="3" name="msg" id="msg">Your Message</textarea><br />
</div>
<input type="button" onclick="return checkForm('contactform');" id="sb" value="Submit" class="submitbtn" />
</div>
</form>
Your checkform function behaves like it should.
However here is a possible correction
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name" || $("#name").val() == 'Field cannot be blank' ) {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email" || $("#email").val() = 'Field cannot be blank' ) {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message" || $("#msg").val() == 'You forgot to enter your message' ) {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
Please look at http://en.wikipedia.org/wiki/Idempotence too.

Categories