Validating group of radio buttons - javascript

function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
for(var i=0; i<form.elements.length; i++)
{
if(form.elements[i].checked)
{
valid = true;
}
else
{
alert("No option selected!");
valid = false;
}
}
return valid;
};
This is my JavaScript function to validate group of radio buttons to check if atleast one of them is selected. And, the one below is my form.
<form name="myForm" font-size="75px;" action ="serv" method="get" onsubmit="return validate();" >
<hr/>
Enter the 1st number: <input type="text" name="a" id="a" /><br/>
Enter the 2st number: <input type="text" name="b" id="b"/><br/><br/>
<label>Add</label><input type="radio" name="option" value="Add" id="r1" /><br/>
<label>Subtract</label><input type="radio" name="option" value="Subtract" id="r2" /><br/>
<label>Multiply</label><input type="radio" name="option" value="Multiply" id="r3" /><br/>
<label>Divide</label><input type="radio" name="option" value="Divide" id="r4" /><br/>
<input type="submit" value="Submit" />
</form>
When i give input and no radio button is selected it should alert the user, but its not happening. Can someone guide where I've gone wrong? And help me out with this? I know there might be lot of duplicates, but I've tried them all to no avail. When i click submit without selecting the radio button it gives me a blank page. Any help is appreciated. Thanks.

Try this, Check the demo here Fiddle
function validate()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if(a.value.length<=0 || b.value.length<=0 || a.value.trim()=="" || b.value.trim()=="")
{
alert("Don't leave the field empty!");
valid = false;
}
if(isNaN(a.value) || isNaN(b.value))
{
alert("Enter a proper number!");
valid = false;
}
var ele = document.getElementsByName("option");
var flag=0;
for(var i=0; i<ele.length; i++)
{
if(ele[i].checked)
{
flag=1;
break;
}
}
if(flag == 0)
{
alert("No option selected!");
valid = false;
}
return valid;
};

Related

Check all conditions in form using jquery

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<h1>USER REGISTRATION</h1>
<br>
<form class="for" name="ureg" method="post" action="">
<fieldset style="margin-right: 900px">
<legend>Registration Form</legend>
<pre>
Name <input class="name" type="text"><span id="errmsg5"></span></input><br><br>
User Name <input class="uname" type="text"><span id="errmsg6"></span></input><br><br>
Password <input class="pass" type="password" name="pass"><span id="errmsg7"></span></input><br><br>
Confirm Password <input class="cpass" type="password" name="cpass"><span id="errmsg1"></span></input><br><br>
Email <input type="email"></input><br><br>
Gender <input type="radio" name="gender" value="male">Male</input><input type="radio" name="gender" value="female">Female</input><br><br>
Country <select name="country" style="width: 175px;">
<option value="india">India</option>
<option value="pakistan">Pakistan</option>
<option value="sri lanka">Sri Lanka</option>
<option value="china">China</option>
<option value="china">Japan</option>
<option value="china">Bangladesh</option>
</select><br><br>
Mobile <input class="mob" type="number"><span id="errmsg3"></span></input><br><br>
Age <input class="age" type="number" name="age"><span id="errmsg2"></span></input><br><br>
D.O.B <input type="date"></input><br><br>
Address
<textarea rows="4" cols="50" name="address"></textarea><br><br>
Pincode <input class="pin" type="number"><span id="errmsg4"></span></input><br><br>
<input id="submit" type="submit" value="SUBMIT"> <input id="reset" type="submit" value="RESET">
</pre>
</fieldset>
</form>
<script type="text/javascript">
$(function () {
$(".cpass").change(function () {
var password = $(".pass").val();
var confirmPassword = $(".cpass").val();
if (password != confirmPassword)
{
$("#errmsg1").text(" Password does not match");
return false;
}
else
{
$("#errmsg1").text("");
return true;
}
});
$(".age").change(function () {
$("#errmsg2").text(" ");
var n = $(".age").val();
if (n < 18) {
$("#errmsg2").text( " Age should be > 18");
return false;
}
return true;
});
$(".mob").change(function () {
$("#errmsg3").text( " ");
var mobile = $(".mob").val();
if (mobile.length != 10) {
$("#errmsg3").text( " Not a valid number");
return false;
}
return true;
});
$(".pin").change(function () {
$("#errmsg4").text( " ");
var mobile = $(".pin").val();
if (mobile.length != 6) {
$("#errmsg4").text( " Not a Valid Pincode");
return false;
}
return true;
});
$(".name").change(function () {
$("#errmsg5").text( " ");
var name = $(".name").val();
var pattern = new RegExp("^[A-z]+$");
if (!pattern.test(name)) {
$("#errmsg5").text( " Name should contain only letters");
return false;
}
return true;
});
$(".uname").change(function () {
$("#errmsg6").text( " ");
var uname = $(".uname").val();
var pattern = new RegExp("^[A-z0-9]+$");
if (!pattern.test(uname)) {
$("#errmsg6").text( " User Name should contain only numbers and alphabets");
return false;
}
return true;
});
$(".pass").change(function () {
$("#errmsg7").text(" ");
var pass = $(".pass").val();
if(pass.length>8)
{
var caps = /[A-Z]/.test(pass);
var small = /[a-z]/.test(pass);
var num= /[0-9]/.test(pass);
var sp=/\W|_/.test(pass);
if(caps&&small&&num&&sp)
{
$("#errmsg7").text("");
return true;
}
else
{
$("#errmsg7").text("Password should be of minimum 8 characters and contain atleast 1 upper case, 1 lower case, 1 digit and 1 special characters");
return false;
}
}
else
{
$("#errmsg7").text("Password should be of minimum 8 characters and contain atleast 1 upper case, 1 lower case, 1 digit and 1 special characters");
return false;
}
});
});
</script>
</body>
</html>
this my code for validating the form. Once the SUBMIT is pressed i want to check the values one more time. or alternatively the the submit would work only when all the conditions are true. is there any way to do it?
You can target the form and check for the 'submit' event, then return false if the values aren't right. Alternatively, you could preventDefault on the event with e.preventDefault(); and submit the form with AJAX.
EDIT: Here's the short version of what I generally do as a first-pass for form validation. Note that this is the absolute least you should be doing. Users can simply remove the required attribute, and get by your first-pass validation, so you should always check for the absolutely required fields in addition, as well as check on the server-side after sanitizing the input. (As in, remove disallowed chars then check for proper data.)
$('form.validate').on('submit', function(e, el) {
var inputs = $(this).find('input[required]'),
empty = $(inputs).map(function(e, el) {
if (el.value === '') {
return el;
}
});
if (empty.length > 0) {
return false;
}
})

Javascript - Not Reversing the show/hide

I have created a fiddle
Would like to have the user hit 'yes' and it show the # field and then hit 'no' to hide it. Do I need another function on the 'no' to do this?
var empNumber, radios;
function showReqEmp() {
if (!radiosChecked()) {
empNumber.style.display = 'none';
} else {
empNumber.style.display = 'block';
}
}
function showReqEmp(id) {
var a = document.getElementById(id);
if (!radiosChecked())
a.style.display = 'none';
else
a.style.display = 'block';
}
function radiosChecked() {
var radios = document.getElementsByName('returning_employee');
for (var i = 0; i < radios.length; i++)
if (radios[i].checked) return true;
return false;
}
showReqEmp('requiredNum');
showReqEmp('requiredNumText');
<font color="Red">*</font>Returning Employee:</td>
<input type="radio" name="returning_employee" value="Yes" onclick="showReqEmp('requiredNum'); showReqEmp('requiredNumText')">Yes
<input type="radio" name="returning_employee" value="No" onclick="showReqEmp('requiredNumText'); showReqEmp('requiredNum')" />No
<lable id="requiredNumText" style="display:none"><font color="Red">*</font>Employee Number:</lable>
<lable id="requiredNum" style="display:none">
<input type="text" id="employee_number" name="employee_number" placeholder="123456789">
Ok so now I ran into this issue with the validation.
Fiddle2
The show/hide works but i cant get the validation to check if they entered data after hitting 'yes'
var numberExp = /^[0-9\-]+$/;
function validate()
{
if(document.newempRequest.returning_employee.checked && !(document.newempRequest.employee_number.value.match(numberExp)))
{
alert("Please provide the employee number");
document.newempRequest.employee_number.focus();
return false;
}
return true;
}
I have tried to alter the input tags to differ the yes/no but that breaks the show/hide
The HTML code is same as above.
Simply modify the radiosChecked function to return true only if the Yes checkbox is checked.
function radiosChecked() {
var radios = document.getElementsByName('returning_employee')[0];
return radios.checked;
}
The original Code:
var radios = document.getElementsByName('returning_employee');
for (var i = 0; i < radios.length; i++)
if (radios[i].checked) return true;
return false;
Would return true even if any of the check box in the group is checked. Hence the toggling would not happen.
You can do it CSS-only, without JS:
#requiredNum {
display: none;
}
#returning_employee_yes:checked ~ #requiredNum {
display: block;
}
*Returning Employee:
<input type="radio" name="returning_employee"
id="returning_employee_yes" value="Yes" />
<label for="returning_employee_yes">Yes</label>
<input type="radio" name="returning_employee"
id="returning_employee_no" value="No" />
<label for="returning_employee_no">No</label>
<label id="requiredNum">
*Employee Number:
<input type="text" id="employee_number"
name="employee_number" placeholder="123456789" />
</label>

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

validation of input text field in html using javascript

<script type='text/javascript'>
function required()
{
var empt = document.forms["form1"]["Name"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Validation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var tags = document.getElementsByTagName("input");
var radiotags = document.getElementsByName("gender");
var compareValidator = ['compare'];
var formtag = document.getElementsByTagName("form");
function validation(){
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
//Validation for Textbox Start
if(tags[i].type == "text"){
if(tagval == "" || tagval == null){
var lbl = $(tags[i]).prev().text();
lbl = lbl.replace(/ : /g,'')
//alert("Please Enter "+lbl);
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Please Enter "+lbl+"</span>");
$("#"+tagid).focus();
//return false;
}
else if(tagval != "" || tagval != null){
$(".span"+tagid).remove();
}
//Validation for compare text in two text boxes Start
//put two tags with same class name and put class name in compareValidator.
for(var j=0;j<compareValidator.length;j++){
if((tagval != "") && (tagclass.indexOf(compareValidator[j]) != -1)){
if(($('.'+compareValidator[j]).first().val()) != ($('.'+compareValidator[j]).last().val())){
$("."+compareValidator[j]+":last").after("<span style='color:red;' class='span"+tagid+"'>Invalid Text</span>");
$("span").prev("span").remove();
$("."+compareValidator[j]+":last").focus();
//return false;
}
}
}
//Validation for compare text in two text boxes End
//Validation for Email Start
if((tagval != "") && (tagclass.indexOf('email') != -1)){
//enter class = email where you want to use email validator
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(tagval)){
$(".span"+tagid).remove();
return true;
}
else{
$(".span"+tagid).remove();
$("#"+tagid).after("<span style='color:red;' class='span"+tagid+"'>Email is Invalid</span>");
$("#"+tagid).focus();
return false;
}
}
//Validation for Email End
}
//Validation for Textbox End
//Validation for Radio Start
else if(tags[i].type == "radio"){
//enter class = gender where you want to use gender validator
if((radiotags[0].checked == false) && (radiotags[1].checked == false)){
$(".span"+tagid).remove();
//$("#"+tagid").after("<span style='color:red;' class='span"+tagid+"'>Please Select Your Gender </span>");
$(".gender:last").next().after("<span style='color:red;' class='span"+tagid+"'> Please Select Your Gender</span>");
$("#"+tagid).focus();
i += 1;
}
else{
$(".span"+tagid).remove();
}
}
//Validation for Radio End
else{
}
}
//return false;
}
function Validate(){
if(!validation()){
return false;
}
return true;
}
function onloadevents(){
tags[tags.length -1].onclick = function(){
//return Validate();
}
for(var j=0;j<formtag.length;j++){
formtag[j].onsubmit = function(){
return Validate();
}
}
for(var i=0;i<tags.length;i++){
var tagid = tags[i].id;
var tagval = tags[i].value;
var tagtit = tags[i].title;
var tagclass = tags[i].className;
if((tags[i].type == "text") && (tagclass.indexOf('numeric') != -1)){
//enter class = numeric where you want to use numeric validator
document.getElementById(tagid).onkeypress = function(){
numeric(event);
}
}
}
}
function numeric(event){
var KeyBoardCode = (event.which) ? event.which : event.keyCode;
if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)){
event.preventDefault();
$(".spannum").remove();
//$(".numeric").after("<span class='spannum'>Numeric Keys Please</span>");
//$(".numeric").focus();
return false;
}
$(".spannum").remove();
return true;
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", onloadevents, false);
}
//window.onload = onloadevents;
</script>
</head>
<body>
<form method="post">
<label for="fname">Test 1 : </label><input type="text" title="Test 1" id="fname" class="form1"><br>
<label for="fname1">Test 2 : </label><input type="text" title="Test 2" id="fname1" class="form1 compare"><br>
<label for="fname2">Test 3 : </label><input type="text" title="Test 3" id="fname2" class="form1 compare"><br>
<label for="gender">Gender : </label>
<input type="radio" title="Male" id="fname3" class="gender" name="gender" value="Male"><label for="gender">Male</label>
<input type="radio" title="Female" id="fname4" class="gender" name="gender" value="Female"><label for="gender">Female</label><br>
<label for="fname5">Mobile : </label><input type="text" title="Mobile" id="fname5" class="numeric"><br>
<label for="fname6">Email : </label><input type="text" title="Email" id="fname6" class="email"><br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
function hasValue( val ) { // Return true if text input is valid/ not-empty
return val.replace(/\s+/, '').length; // boolean
}
For multiple elements you can pass inside your input elements loop their value into that function argument.
If a user inserted one or more spaces, thanks to the regex s+ the function will return false.
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
before using above code you have to add the gen_validatorv31.js js file
For flexibility and other places you might want to validated. You can use the following function.
`function validateOnlyTextField(element) {
var str = element.value;
if(!(/^[a-zA-Z, ]+$/.test(str))){
// console.log('String contain number characters');
str = str.substr(0, str.length -1);
element.value = str;
}
}`
Then on your html section use the following event.
<input type="text" id="names" onkeyup="validateOnlyTextField(this)" />
You can always reuse the function.

Javascript validation for multiple textboxes

I am having some trouble figuring out how to validate my textboxes using js. I have 10 textboxes, the user can fill out any number 1-10, but cant fill out 0. Here is the js that I have written, but it only returns true if all 10 textboxes are filled, rather than just checking if one is filled.
function submitIt() {
if (document.isForm.Student_ID.value == null) {
alert ("You must enter a Colleague ID.");
return false;
} else {
return true;
}
}
And here is the form.....
<form name="isForm" onSubmit="return submitIt()">
<input name="Student_ID" type="text" id="idField1" />
<input name="Student_ID" type="text" id="idField2" />
<input name="Student_ID" type="text" id="idField3" />
<input name="Student_ID" type="text" id="idField4" />
<input name="Student_ID" type="text" id="idField5" />
<input name="Student_ID" type="text" id="idField6" />
<input name="Student_ID" type="text" id="idField7" />
<input name="Student_ID" type="text" id="idField8" />
<input name="Student_ID" type="text" id="idField9" />
<input name="Student_ID" type="text" id="idField10" />
<input name="SUBMIT" type="submit" />
</form>
I realize that I could change all of the names, and check each one, but I am trying to avoid that much clutter in my code, and am curious the best way to do this. Any help is appreciated, thanks!
You can get a collection of all these textboxes with document.getElementsByName. Then loop through them, and make sure at least one is filled in:
var allTbs = document.getElementsByName("Student_ID");
var valid = false;
for (var i = 0, max = allTbs.length; i < max; i++) {
if (allTbs[i].value) {
valid = true;
break;
}
}
DEMO
Function is iterating by all of the student text boxes and return true if some element is filled out. Protected against that if input contain only spaces :)
function submitIt() {
for( var i = 0, t = document.getElementsByName( "Student_ID" ), l = t.length; i < l; i++ )
if( t[i].value && !/^\s+$/.test( t[i].value ) )
return true;
return false
}
Demo on: http://jsfiddle.net/hhD2x/
you can use jquery.
add common class name for all your textboxes i.e.
<input name="Student_ID" type="text" id="idField1" class="student" />
now in js function
function submit()
{
$('.student').each(function() {
if($(this).val() == '' || $(this).val() == null)
{
// your error message
return false;
}
}
}
this function check all the elements with student class.
$('input[type="text"], select,
:input[type="date"],
:input[type="email"],
:input[type="radio"]').each(function () {
if ($.trim($(this).val()) == '' ) {
// your error message here
isValid = false;
}
});

Categories

Resources