How to apply validation if input fields are empty? - javascript

I am applying validations to all the input where values are left blank. Whenever any input is blank and user will click on save button them we add class has-error and display message in small tag.
I have written following html.
<div class="form-group">
<label class="col-sm-3 control-label">Academic Year *</label>
<div class="col-sm-7"><input type="text" id="academicyearname" maxlength="4" class="form-control only-numbers">
<small id="year_nameHelp" class="text-danger hide">
Academic Year is Required
</small>
</div>
</div>
<div class="form-group" id="dateStartsOn">
<label class="col-sm-3 control-label">Starts On *</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input aria-required="true" id="startson" class="form-control block-keypress" type="text"
onclick="css()">
<small id="start_dateHelp" class="text-danger hide">
Start Date is Required
</small>
</div>
</div>
</div>
<div class="form-group" id="dateEndsOn">
<label class="col-sm-3 control-label">Ends On *</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input aria-required="true" id="endson" class="form-control block-keypress" type="text" onclick="css()">
<small id="end_dateHelp" class="text-danger hide">
End Date is Required
</small>
</div>
</div>
</div>
...
....
In jquery I am doing following validation on save button click
if((":input").val().trim() =="")
{
$(this).closest(".form-group").addClass( "has-error");
$("small").removeClass('hide');
return;
}
if(academicyearname == "")
{
$("#academicyearname").closest(".form-group").addClass( "has-error");
$("#year_nameHelp").removeClass('hide');
$("#academicyearname").focus();
}
else if(startson == "")
{
$("#startson").closest(".form-group").addClass( "has-error");
$("#start_dateHelp").removeClass('hide');
}
else if(endson == "")
{
$("#endson").closest(".form-group").addClass( "has-error");
$("#end_dateHelp").removeClass('hide');
}
....
The part
if((":input").val().trim() =="")
{
$(this).closest(".form-group").addClass( "has-error");
$("small").removeClass('hide');
return;
}
is not working accordingly. I mean it should be able to dynamically detect which inputs are empty and then add error class to the corresponding input where value is "".

You can use jquery validator js's blank element plugin and you can use it as follows:
$( "input:blank" ).css( "background-color", "#bbbbff" );
Have a look at below:
https://jqueryvalidation.org/blank-selector/
It also can be applied at id and class level.

Try using
var result = $("input:text").val().trim();
if(result == ""){
//do something
}

var vendorError = false;
$(".vendorForm input").each(function () {
if ($(this).val() == '') {
jAlert('Required', 'empty');
vendorError = true;
var div = document.getElementById($(this).attr('id'));
// show meg logic
if (div.style.display !== "block") {
div.style.display = "block";
}
return false;
}
})
if (vendorError) {
return false;
}
HTML file
<div id="vendorForm" class="form-group">
<label class="col-sm-3 control-label">Academic Year *</label>
<div class="col-sm-7"><input type="text" id="academicyearname" maxlength="4" class="form-control only-numbers">
<small id="year_nameHelp" class="text-danger hide">
Academic Year is Required
</small>
</div>
</div>
<div class="form-group" id="dateStartsOn">
<label class="col-sm-3 control-label">Starts On *</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input id="startson" value="" class="form-control block-keypress" type="text"
onclick="css()">
<small id="start_dateHelp" class="text-danger hide">
Start Date is Required
</small>
</div>
</div>
</div>
<div class="form-group" id="dateEndsOn">
<label class="col-sm-3 control-label">Ends On *</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
<input id="endson" value="" class="form-control block-keypress" type="text" onclick="css()">
<small id="end_dateHelp" class="text-danger hide">
End Date is Required
</small>
</div>
</div>
</div>
...
....

I understood and somewhat same module i also designed. You can make the use of modal and give that id to in the js and on click button you can run the function in your js file. See my html page:
<div class="modal-body">
<div class="form-group">
<form id = "updateForm" onsubmit="return false" enctype="multipart/form-data">
<div class="left">
<div class="well img_height">
<img id="blah" src="admin_resources/images/user-icon.png"/>
</div>
<div>
<input type="file" name="myfile" onchange="readURL(this);" id="myfile"/>
</div>
</div>
<label for="emp_id">Employee Id:</label>
<input type="text" class="form-control" id="emp_id" name="employeeId" >
<p id="valid_msg_employee_id" class="error_message"></p>
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="firstName" name="firstName" >
<p id="valid_msg_fname" class="error_message"></p>
<label for="lname">Last Name:</label>
<input type="text"class="form-control" id="lastName" name="lastName">
<p id="valid_msg_lname" class="error_message"></p>
<label for="designation">Designation:</label> <br/>
<select name="designation" id="dropdown" class="form-control">
<option value="Select">Select Designation</option>
<option value="manager">Manager</option>
<option value="HR">HR</option>
<option value="Tech Lead">Tech Lead</option>
<option value="QA Lead">QA Lead</option>
<option value="Developer">Developer</option>
<option value="QA-Automation">QA-Automation</option>
<option value="QA-Manual">QA-Manual</option>
<option value="Software Trainee">Software Trainee</option>
<option value="Sr. Software Quality Engineer">Sr. Software Quality Engineer</option>
<option value="SQE">SQE</option>
<option value="Software Quality Engineer">Software Quality Engineer</option>
<option value="Associate Software Engineer">Associate Software Engineer</option>
<option value="QA Manager">QA Manager</option>
</select>
<p id="valid_msg_designation" class="error_message"></p>
<label for="Doj">Joining Date:</label>
<input type="text" class="form-control" id="doj" name="yearOfJoining" >
<p id="valid_msg_year" class="error_message"></p>
<label for="status">Status:</label> <br/>
<select name="status" id="status" class="form-control">
<option value="active">Active</option>
<option value="inactive">inactive</option>
</select>
<p id="valid_msg_designation" class="error_message"></p>
<p id="valid_msg_year" class="error_message"></p>
<label for="email_id">Email-id:</label>
<input type="email" class="form-control" id="email" name="email">
<p id="valid_msg_email" class="error_message"></p>
<label for="quali">Contact:</label>
<input type="text" class="form-control" id="contact" name="mobileNo">
<p id="valid_msg_contact" class="error_message"></p>
<button type="submit" class="btn btn-default" onclick="updateEmployeeDetail();" data-dismiss="modal">Update</button>
<button type="button" class="btn btn-default" onclick = "deleteEmployee();" data-dismiss="modal">Delete</button>
</form>
</div>
</div>
and you can now add a class "erro_message which will be called on the modal:
the js file is this:
function employeeDetail() {
$("#submit_emp").click(function(event) {
var formValid = employeeDetail.formValidation();
if (formValid) {
var formvalue = new FormData($('#addForm')[0]);
$.ajax({
url: "intranet/addEmployee",
type: "POST",
data: formvalue,
contentType: false,
processData: false,
success: function(response) {
$('#your-modal').modal('toggle');
$("#header_success").empty();
$("#header_success").append("Response");
$("#message_success").empty();
$("#message_success").append(response.message);
$('#addForm').trigger("reset");
},
error: function(e) {
$('#your-modal').modal('toggle');
$("#message_success").empty();
$("#message_success").append(e.message);
}
});
} else {
return false;
}
});
You can add many validations on this input type and can append the messge ypuwant on that particular fied:
Hope this might help you.

This is super simplistic and does NOT do the "validation" by checking for example numeric values, etc. but you wanted/asked for the selector for empty text inputs so this gives that.
// put on some event, used change here:
$('input[type=text]').on('change', function() {
// just clear all
$(".form-group").removeClass("has-error");
$("small").addClass('hide');
// filter those empty ones
$('input[type=text]').filter(function() {
return $(this).val().trim() == "";
}).each(function() {
$(this).closest(".form-group").addClass("has-error");
$(this).parent().find("small").removeClass('hide');
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="form-group">
<label class="col-sm-3 control-label">Academic Year *</label>
<div class="col-sm-7"><input type="text" id="academicyearname" maxlength="4" class="form-control only-numbers">
<small id="year_nameHelp" class="text-danger hide">Academic Year is Required</small>
</div>
</div>
<div class="form-group" id="dateStartsOn">
<label class="col-sm-3 control-label">Starts On *</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i> </span>
<input aria-required="true" id="startson" class="form-control block-keypress" type="text" >
<small id="start_dateHelp" class="text-danger hide">Start Date is Required</small>
</div>
</div>
</div>
<div class="form-group" id="dateEndsOn">
<label class="col-sm-3 control-label">Ends On *</label>
<div class="col-sm-7">
<div class="input-group date">
<span class="input-group-addon"> <i class="fa fa-calendar"></i> </span>
<input aria-required="true" id="endson" class="form-control block-keypress" type="text" >
<small id="end_dateHelp" class="text-danger hide">End Date is Required</small>
</div>
</div>
</div>

Related

Redirect to form with input value from previous form in Laravel

I'm working with Form in Laravel. In that form have a modal that containts another form.
Here's the screenshot of the Form :
SS1 (I can't post an image because my reputation is not enough)
when I click on New button (besides of Customer Name input text) there will be a modal that containts form to input new customers and new unit. Here's the screenshot of the modal :
SS2
and the idea is,after I complete the input of new customer and unit, the data i've inputted will automatically input the main form.
and this is what I've done so far :
$("#main_form2").on("submit", function(event) {
event.preventDefault();
value = $(this).serialize();
alert(value);
$.ajax({
type: 'post',
url: $(this).attr('action'),
data: {
'value': value
},
success: function(data) {
$('#customer_id').val(data.customer_id)
$('#customer_name').val(data.customer_name)
$('#customer_pic').val(data.customer_pic)
$('#unit_province').val(data.customer_province)
$('#unit_cities').val(data.customer_site)
$('#unit_sn').val(data.unit_sn)
$('#unit_brand').val(data.unit_brand)
$('#unit_type').val(data.unit_type)
$('#unit_model').val(data.unit_model)
},
error: function() {}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="{{route('ticket-service/store')}}" method="POST" id="main_form">
#csrf
<div class="panel panel-inverse">
<div class="panel-heading ui-sortable-handle">
<h4 class="panel-title">Ticket Service Create</h4>
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
<i class="fa fa-minus"></i>
</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="ticket_inquiry_from"><b>Inquiry From</b> <span class="text-danger">*</span></label>
<select class="form-control ticket_inquiry_from form-control-sm" name="ticket_inquiry_from" id="ticket_inquiry_from">
<option value="">Select Option</option>
<option value="Phone">Phone</option>
<option value="Website">Website</option>
<option value="WhatsApp">WhatsApp</option>
<option value="Email">Email</option>
</select>
<span class="text-danger error-text ticket_inquiry_from_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="ticket_inquiry_to"><b>Inquiry To</b> <span class="text-danger">*</span></label>
<select class="form-control ticket_inquiry_to form-control-sm" name="ticket_inquiry_to" id="ticket_inquiry_to">
<option value="">Select Option</option>
<option value="Marketing">Marketing</option>
<option value="Service">Service</option>
<option value="Sparepart">Sparepart</option>
</select>
<span class="text-danger error-text ticket_inquiry_to_error"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="ticket_inquiry_pic"><b>Inquiry PIC</b><a class="text-danger"> *</a></label>
<select class="js-example-basic-multiple" class="form-control form-control-sm form-select form-select-sm" name="ticket_inquiry_pic[]" multiple="multiple" style="width:100%;">
#foreach(SiteHelpers::get_user_all() as $pic)
<option value="{{$pic->id}}" <?php echo (old( 'ticket_inquiry_pic')==$ pic->user_name) ? 'selected' : ''?>>{{$pic->user_name}}</option>
#endforeach
</select>
<span class="text-danger error-text ticket_inquiry_pic_error"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="ticket_date"><b>Ticket Date</b></label>
<div class="col-sm-13">
<input type="text" class="form-control form-control-sm" name="ticket_date" value="{{date('Y/m/d')}}" readonly/>
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="service_request_date"><b>Service Request Date</b> <span class="text-danger">*</span></label>
<div class="col-sm-13">
<div class="input-group date" id="datepicker-disabled-past" data-date-format="dd-mm-yyyy" data-date-start-date="Date.default">
<input type="text" class="form-control form-control-sm" name="service_request_date" value="{{old('service_request_date')}}" />
<div class="input-group-addon"><i class="fa fa-calendar"></i></div>
</div>
<span class="text-danger error-text service_request_date_error"></span>
</div>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="liability_charges"><b>Charges To</b> <span class="text-danger">*</span></label>
<select class="form-control liability_charges form-control-sm" name="liability_charges" id="liability_charges">
<option value="">Select Option</option>
<option value="Principal">Principal</option>
<option value="Dept. Marketing">Dept. Marketing</option>
<option value="Dept. Part">Dept. Part</option>
<option value="Dept. Service">Dept. Service</option>
<option value="Customer">Customer</option>
<option value="Free Charge">Free Charge</option>
</select>
<span class="text-danger error-text liability_charges_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="ticket_category"><b>Category</b> <span class="text-danger">*</span></label>
<select class="form-control category form-control-sm" name="ticket_category" id="ticket_category">
<option value="">Select Category</option>
<option value="Inspection">Inspection</option>
<option value="Commissioning">Commissioning</option>
<option value="Regular Service">Regular Service</option>
<option value="Repair / Troubleshooting">Repair / Troubleshooting</option>
<option value="Training">Training</option>
<option value="Warranty">Warranty</option>
<option value="Sparepart">Sparepart</option>
<option value="Unit">Unit</option>
<option value="Other">Other</option>
</select>
<span class="text-danger error-text ticket_category_error"></span>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="customer_id"><b>Customer</b><span class="text-danger"> *</span></label>
<div class="input-group">
<input type="hidden" id="customer_id" name="customer_id" value="{{(isset($data)) ? $data->customer_id : ''}}">
<input type="text" class="form-control form-control-sm" placeholder="Customer Name" id="customer_name" href="{{route('population/popup_media')}}" data-toggle="modal" data-target="#modal-default" value="{{(isset($data)) ? $data->customer_name : ''}}">
<div class="input-group-prepend">
<span style="cursor:pointer;" class="input-group-text form-control-sm" href="#modal-new-customer" id='new-customer' rel='tooltip' data-placement='top' data-toggle='modal' title='Add New Customer'><i class="fa fa-user"></i>&nbsp<b>New</b></span>
</div>
</div>
<span class="text-danger error-text customer_id_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="customer_pic"><b>Customer PIC</b><span class="text-danger"> *</span></label>
<input type="text" class="form-control form-control-sm" id="customer_pic" name="customer_pic" placeholder="Customer PIC">
<span class="text-danger error-text customer_pic_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="customer_phone"><b>Customer Phone</b><span class="text-danger"> *</span></label>
<input type="text" class="form-control form-control-sm" id="customer_phone" name="customer_phone" placeholder="Customer Phone">
<span class="text-danger error-text customer_phone_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="customer_email"><b>Customer Email</b></label>
<input type="text" class="form-control form-control-sm" id="customer_email" name="customer_email" placeholder="Customer Email">
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="unit_sn"><b>Unit SN</b></label>
<input type="text" class="form-control form-control-sm" id="unit_sn" name="unit_sn" placeholder="Unit SN" readonly>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="unit_brand"><b>Unit Brand</b></label>
<input type="text" class="form-control form-control-sm" id="unit_brand" name="unit_brand" placeholder="Unit Brand" disabled>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="category"><b>Unit Type</b></label>
<input type="text" class="form-control form-control-sm" id="category" name="category" placeholder="Type" disabled>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="unit_model"><b>Unit Model</b></label>
<input type="text" class="form-control form-control-sm" id="unit_model" name="unit_model" placeholder="Unit Model" disabled>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="province_name"><b>Unit Province</b> <span class="text-danger">*</span></label>
<select class="form-control form-control-sm province_name" name="unit_province" id="unit_province">
<option value="" disabled="true" selected="true">Choose Province</option>
#foreach(SiteHelpers::get_province() as $province)
<option value="{{$province->id}}">{{$province->province_name}}</option>
#endforeach
</select>
<span class="text-danger error-text unit_province_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="cities"><b>Unit City</b> <span class="text-danger">*</span></label>
<select class="form-control form-control-sm cities" name="unit_cities" id="unit_cities">
<option value="0" disabled selected>Select City</option>
</select>
<span class="text-danger error-text unit_cities_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="unit_site"><b>Site/Workshop Address</b> <span class="text-danger">*</span></label>
<input type="text" class="form-control form-control-sm" id="unit_site" name="unit_site" placeholder="Unit Site">
<span class="text-danger error-text unit_site_error"></span>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="unit_status"><b>Unit Status</b> <span class="text-danger">*</span></label>
<select class="form-control category form-control-sm" name="unit_status" id="unit_status">
<option value="">Select Status</option>
<option value="Breakdown">Breakdown</option>
<option value="Stand By">Running</option>
<option value="Working">Stand By</option>
</select>
<span class="text-danger error-text unit_status_error"></span>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ticket_complaints"><b>Informed Issue</b> <span class="text-danger">*</span></label>
<textarea name="ticket_complaints" id="ticket_complaints" class="form-control form-control-sm" style="height: 99px;"></textarea>
<span class="text-danger error-text ticket_complaints_error"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="ticket_notes"><b>Notes</b></label>
<textarea name="ticket_notes" id="ticket_notes" class="form-control form-control-sm" style="height: 99px;"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="ticket_status"><b>Ticket Status</b> </label>
<select class="form-control category form-control-sm" name="ticket_status" id="ticket_status">
<option value="OPEN">OPEN</option>
<option value="Finished">Finished</option>
</select>
<span class="text-danger error-text ticket_status_error"></span>
</div>
</div>
<div class="col-md-3 ticket-detail" style="display:none;">
<div class="form-group">
<label for="ticket_guidance"><b>Ticket Guidance</b> <span class="text-danger">*</span></label>
<select class="form-control category form-control-sm" name="ticket_guidance" id="ticket_guidance">
<option value="">Select Guidance</option>
<option value="Phone">Phone</option>
<option value="Other">Other</option>
</select>
<span class="text-danger error-text ticket_guidance_error"></span>
</div>
</div>
<div class="col-md-6 ticket-detail" style="display:none;">
<div class="form-group">
<label for="ticket_guide_name"><b>Guide Name</b> <span class="text-danger">*</span></label>
<input type="text" name="ticket_guide_name" id="ticket_guide_name" class="form-control form-control-sm">
<span class="text-danger error-text ticket_guide_name_error"></span>
</div>
</div>
</div>
<button type="submit" class="btn btn-sm btn-success m-r-5">Submit</button>
Cancel
</div>
</div>
</form>
<!-- the modal -->
<div class="modal fade" id="modal-new-customer" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add New Customer</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<form action="{{ route('customer/storeWithPopulation') }}" method="POST" id="main_form2">
#csrf
<div class="modal-body">
<div class="panel-body">
<label for="unit"><b><i>Customer(s)</i></b></label>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="customer_name"><b>Customer Name</b> <span class="text-danger">*</span></label>
<input type="hidden" name="customer_id" value="temp">
<input type="hidden" name="unit_status_stock" value="DELIVERED">
<input type="text" class="form-control" id="customer_name" name="customer_name" placeholder="Customer Name" value="{{old('customer_name')}}">
<span class="text-danger error-text customer_name_error"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="PIC"><b>PIC</b></label>
<input type="text" class="form-control" id="customer_pic" name="customer_pic" placeholder="PIC" value="{{old('customer_pic')}}">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="province_name"><b>Unit Province</b> <span class="text-danger">*</span></label>
<select class="form-control province_name" name="customer_province" id="customer_province">
<option value="" disabled="true" selected="true">Choose Province</option>
#foreach(SiteHelpers::get_province() as $province)
<option value="{{$province->id}}">{{$province->province_name}}</option>
#endforeach
</select>
<span class="text-danger error-text customer_province_error"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="cities"><b>Site</b> <span class="text-danger">*</span></label>
<select class="form-control cities" name="customer_site" id="customer_site">
<option value="0" disabled selected>Select City</option>
</select>
<span class="text-danger error-text customer_site_error"></span>
</div>
</div>
</div>
</br>
<label for="unit"><b><i>Population(s)</i></b></label>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="brand"><b>Brand</b><span class="text-danger"> *</span></label>
<select class="form-control brand form-control-sm" name="unit_brand" id="unit_brand">
<option value="">Chose Brand</option>
#foreach($brands as $brand)
<option value="{{$brand->brand}}">{{$brand->brand}}</option>
#endforeach
</select>
<span class="text-danger error-text unit_brand_error"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="model"><b>Category</b><span class="text-danger"> *</span></label>
<select class="form-control category form-control-sm" name="unit_category" id="unit_category">
<option value="" disabled>Select Category</option>
</select>
<span class="text-danger error-text unit_category_error"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 tes">
<div class="form-group">
<label for="model"><b>Model</b><span class="text-danger"> *</span></label>
<select class="form-control model form-control-sm" name="unit_model" id="unit_model">
<option value="" disabled>Select Model</option>
</select>
<span class="text-danger error-text unit_model_error"></span>
</div>
<div class="form-group">
<label for="serial_number"><b>Serial Number</b><span class="text-danger"> *</span></label>
<input type="text" class="form-control form-control-sm" id="unit_sn" name="unit_sn" placeholder="Unit Serial Number">
<span class="text-danger error-text unit_sn_error"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="year"><b>Unit Year</b><span class="text-danger"> *</span></label>
<input type="number" class="form-control form-control-sm" id="unit_year" name="unit_year" placeholder="Unit Year">
<span class="text-danger error-text unit_year_error"></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer" style="background-color:#cccccc;">
Close
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
here's my Controller :
public function storeWithPopulation(Request $request){
abort_unless(\Gate::allows('master-customer-create'),403);
$validator = Validator::make($request->all(),Customer::$createRules,Customer::$customMessage);
$validator2 = Validator::make($request->all(),Population::$createRules,Population::$customMessage);
if(!$validator->passes() && !$validator2->passes()){
$errors = array_merge($validator->errors()->toArray(),$validator2->errors()->toArray());
return response()->json(['status'=>0, 'error'=>$errors]);
}else{
$last_id = Customer::all()->last();
$customer_id = 'CUST-'.$last_id->id;
$values_customer = [
'customer_id'=>$customer_id,
'customer_name'=>$request->customer_name,
'customer_pic'=>$request->customer_pic,
'customer_site'=>$request->customer_site,
'customer_province'=>$request->customer_province,
];
$values_population = [
'customer_id' => $customer_id,
'unit_model'=>$request->unit_model,
'unit_sn'=>$request->unit_sn,
'unit_year'=>$request->unit_year,
'unit_status_stock'=>$request->unit_status_stock,
];
$new_customer = Customer::create($values_customer);
$new_population = Population::create($values_population);
if( $new_population ){
$brands = DB::table('t_brand')->get();
$data = SiteHelpers::get_population_by_sn($new_population->unit_sn);
return response()->json(['status'=>1, 'url'=>'/service/forms/ticket-service/create',['data'=>$data,'brands'=>$brands]]);
// return response()->json(['status'=>1, 'url'=>'/service/forms/ticket-service/create',['data'=>$data,'brands'=>$brands]]);
}
}
}
The problem is, everytime I succeeded create new customer in the modal it also redirect into the main form,but got refreshed and the main form completely in blank condition. I want to grab all the new customer I've just inputed into the main form.
hopefully somebody can help me. Thank you in advance.

Tabbing validation using html 5 based on browser chrome

I have one html form in that there are three tabs within three div.
i want to submit form on one submit button without console error.
I used below script for tabbed html 5 validation its work but it gives console error on chrome browser, like
An invalid form control with name='campign' is not focusable.
please help if anybudy know about this.
<html>
<body>
<div class="col-md-12 col-sm-12 ad_dealer nav-tabs-menu">
<ul class="nav nav-tabs">
<li class="active" title="Personal Information">
<a data-toggle="tab" href="#per-info">
<span> Personal Information</span></a></li>
<li class="secnd" title="Communication Address">
<a data-toggle="tab" href="#comm-add">
<span> Communication Address</span></a></li>
<li class="secnd" title="Experience & Educational Details">
<a data-toggle="tab" href="#exp-edu">
<span>Exp & Educational Details </span></a></li>
</ul>
</div>
<div class="tab-content dealer-tabs">
<!-- <div class="col-md-12">
<h6 class="gg per_info det-area"><span class="line-center">Personal Information</span></h6>
</div> -->
<div id="per-info" class="tab-pane fade in active row col-sm-12">
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Blood Group<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="blood-grp" id="blood-grp" title="Please Select Blood Group" required oninvalid="this.setCustomValidity('Please Select Blood Group')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="1">A+ </option>
<option value="2">A-</option>
<option value="2">AB+</option>
<option value="2">AB-</option>
<option value="2">B+</option>
<option value="2">B-</option>
<option value="2">O+</option>
<option value="2">O-</option>
</select>
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label" for="">Date of Birth<span class="requerido">*</span></label>
<div class="col-md-6">
<input type="text" id="enqdate" name="enqdate" value="" class="form-control datepicker" placeholder="dd-mmm-yyyy" title="Please Enter Date of Birth" required oninvalid="this.setCustomValidity('Please Enter Date of Birth')" onChange="setCustomValidity('')" onkeypress = "return false; event.charCode >= 48 && event.charCode <= 57">
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Marital Status<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="blood-grp" id="blood-grp" title="Please Select Marital Status" required oninvalid="this.setCustomValidity('Please Select Marital Status')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="1">Married </option>
<option value="2">Unmarried</option>
<option value="3">Divorced </option>
<option value="4"> Widowed</option>
</select>
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label" for="">Wedding Date</label>
<div class="col-md-6">
<input type="text" id="enqdate" name="enqdate" value="" class="form-control datepicker" placeholder="dd-mmm-yyyy" title="Please Enter Wedding Date">
</div>
</div>
</div>
<div class="clearfix"> </div>
<!-- <div class="col-md-12">
<h6 class="gg cust_mar det-area"><span class="line-center">Alternate Information</span></h6>
</div> -->
<div class="clearfix"> </div>
<div div id="comm-add" class="tab-pane fade row col-sm-12">
<div class="comm-top">
<div class="form-group row col-sm-6 address-sec" id="campa">
<label class="col-md-4 form-control-label" for="">Permanent Address<span class="requerido">*</span></label>
<div class="col-md-6">
<input type="text" id="campign" name="campign" class="form-control" placeholder="Permanent Address" title="Please Enter Permanent Address" required oninvalid="this.setCustomValidity('Please Enter Permanent Address')" onChange="setCustomValidity('')" style='margin-bottom:5px;' maxlength="250">
<input type="text" id="campign" name="campign" class="form-control" placeholder="" title="" style='margin-bottom:5px;'>
<input type="text" id="campign" name="campign" class="form-control" placeholder="" title="">
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Permanent Village<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="per-vill" id="per-vill" title="Please Select Permanent Village" required oninvalid="this.setCustomValidity('Please Select Permanent Village')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="Marwad ">Marwad </option>
<option value="Thergaon">Thergaon</option>
<option value="Sarangkheda">Sarangkheda</option>
</select>
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Permanent Tehsil<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="per-teh" id="per-teh" title="Please Select Permanent Tehsil" required oninvalid="this.setCustomValidity('Please Select Permanent Tehsil')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="Amalner ">Amalner </option>
<option value="Mulshi">Mulshi</option>
<option value="Mulshi">shada</option>
</select>
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Permanent District<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="per-dis" id="per-dis" title="Please Select Permanent District" required oninvalid="this.setCustomValidity('Please Select Permanent District')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="Jalgaon ">Jalgaon </option>
<option value="Pune">Pune</option>
<option value="Mulshi">Mulshi</option>
</select>
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Permanent State<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="blood-grp" id="blood-grp" title="Please Select Permanent State" required oninvalid="this.setCustomValidity('Please Select Permanent State')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="1">Maharashtra </option>
<option value="2">Punjab</option>
</select>
</div>
</div>
<div class="form-group row col-sm-6 has-feedback">
<label class="col-md-4 form-control-label" for="">Permanent Pin Code<span class="requerido">*</span></label>
<div class="col-md-6">
<input name="myInput_DRS" class="form-control"
onkeypress="return isNumeric(event)"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "10"
min = "1"
max = "10" />
<!-- <input type="text" id="pincode" name="pincode" class="form-control" placeholder="Permanent Pin Code" title="Please Enter Permanent Pin Code" required="" pattern="[0-9]{6}" oninvalid="InvalidMsg(this,'Please Enter Valid Pin Code','Please Enter Pin Code');" oninput="InvalidMsg(this,'Please Enter Valid Pin Code','');" onpaste="return false" onChange="setCustomValidity('')" maxlength="6" onKeyPress="return isNumberKey(event)" onKeyUp="return isNumberKeyWithMark(event,'pincode','validateMark')" /> -->
<span class="glyphicon glyphicon-ok form-control-feedback" value="" id="validateMark" style="display:none;"></span>
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label" for="">Permanent Contact No<span class="requerido">*</span></label>
<div class="col-md-6">
<input type="text" id="percontactno" name="percontactno" value="" class="form-control" placeholder="Permanent Contact No" title="Please Enter Permanent Contact No" required="" pattern="[0-9]{1,20}" onpaste="return false" oninvalid="InvalidMsg(this,'Please Enter Valid Permanent Contact No','Please Enter Permanent Contact No');" oninput="InvalidMsg(this,'Please Enter Valid Permanent Contact','');" onkeyup="inavlidMsgKeyUp(this,event,'Please Enter Permanent Contact No');" onKeyPress="return isNumberKey(event)" onChange="setCustomValidity('');" maxlength="20"/>
</div>
</div>
</div><!--comm-top-->
<div class="clearfix"> </div>
<div class="clearfix"> </div>
<div id="exp-edu" class="tab-pane fade row col-sm-12">
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label" for="">Experience (In Years)<span class="requerido">*</span></label>
<div class="col-md-6">
<input type="text" id="exp" name="exp" value="" class="form-control" placeholder="Experience" title="Please Enter Experience" required="" pattern="^[0-9]+(\.[0-9]{1,2})?$" oninvalid="InvalidMsg(this,'Please Enter valid Experience','Please Enter Experience');" oninput="InvalidMsg(this,'Please valid Enter Experience','');" onkeyup="inavlidMsgKeyUp(this,event,'Please Enter Experience');" onchange="setCustomValidity('')" maxlength="10" onKeyPress="return isNumberKey(event)">
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label" for="">Salary Per Month<span class="requerido">*</span></label>
<div class="col-md-6">
<input type="text" id="salpermonth" name="salpermnth" value="" class="form-control" placeholder="Salary Per Month" title="Please Enter Salary Per Month" required="" pattern="^[0-9]+(\.[0-9]{1,2})?$" oninvalid="InvalidMsg(this,'Please Enter Valid Salary Per Month','Please Enter Salary Per Month');" oninput="InvalidMsg(this,'Please Enter Salary Per Month','');" onkeyup="inavlidMsgKeyUp(this,event,'Please Enter Salary Per Month');" onChange="setCustomValidity('')" maxlength="40" onKeyPress="return isNumberKey(event)">
</div>
</div>
<div class="form-group row col-sm-6 ">
<label class="col-md-4 form-control-label " for="">Education<span class="requerido">*</span></label>
<div class="col-md-6">
<select class="form-control opt " name="edu" id="edu" title="Please Select Education" required oninvalid="this.setCustomValidity('Please Select Education')" onChange="setCustomValidity('')">
<option class="service-small" value="">Select</option>
<option value="1">Diploma</option>
<option value="2">BE</option>
<option value="3">Graduation</option>
<option value="4">Post Graduation</option>
</select>
</div>
</div>
</div>
</div><!--tab-content-->
</div>
<div class="card-footer en_footer">
<button type="submit" title="Submit" id="sub" class="btn btn-sm no_radius btn btn-success">Submit</button>
<button type="button" id="MyReset" title="Reset" class="btn btn-sm no_radius btn-primary">Reset</button>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$('#sub').click(function(evt){ // submit button click event
var $myForm = $('#AddDealerEmployee');
if(!$myForm[0].checkValidity()) {
// If the form is invalid, submit it. The form won't actually submit;
// this will just cause the browser to`enter code here` display the native HTML5 error messages.
var flag1=1;
var flag2=1;
var flag3=1;
var inputs = $('#per-info').find("select, textarea, input");
inputs.each(function( index ) {
//console.log($(this));
if ($(this).is("input") && $(this).prop('required') && !$(this)[0].checkValidity()) {
flag1=0;
}
if ($(this).is("select") && $(this).prop('required') && !$(this)[0].checkValidity()) {
//alert("hi");
flag1=0;
}
});
//comm-add
var inputs = $('#comm-add').find("select, textarea, input");
inputs.each(function( index ) {
//console.log($(this));
if ($(this).is("input") && $(this).prop('required') && !$(this)[0].checkValidity()) {
//alert("hi");
flag2=0;
}
if ($(this).is("select") && $(this).prop('required') && !$(this)[0].checkValidity()) {
//alert("hi");
flag2=0;
}
});
//exp-edu
var inputs = $('#exp-edu').find("select, textarea, input");
inputs.each(function( index ) {
//console.log($(this));
if ($(this).is("input") && $(this).prop('required') && !$(this)[0].checkValidity()) {
//alert("hi");
flag3=0;
}
if ($(this).is("select") && $(this).prop('required') && !$(this)[0].checkValidity()) {
//alert("hi");
flag3=0;
}
});
if(flag1 == 0)
{
if(!$('#per-info').hasClass('active') && $('#comm-add').hasClass('active'))
{
$('.nav-tabs > .active').prev('li').find('a').trigger('click');
}
else
if(!$('#per-info').hasClass('active') && $('#exp-edu').hasClass('active'))
{
$('.nav-tabs li:first').find('a').trigger('click');
}
else
{
}
}
else if(flag2 == 0)
{
if(!$('#comm-add').hasClass('active') && $('#per-info').hasClass('active'))
{
$('.nav-tabs > .active').next('li').find('a').trigger('click');
}
else
if(!$('#comm-add').hasClass('active') && $('#exp-edu').hasClass('active'))
{
$('.nav-tabs > .active').prev('li').find('a').trigger('click');
}
else
{
}
}
else if(flag3 == 0)
{
if(!$('#exp-edu').hasClass('active') && $('#comm-add').hasClass('active'))
{
$('.nav-tabs > .active').next('li').find('a').trigger('click');
}
else
if(!$('#exp-edu').hasClass('active') && $('#per-info').hasClass('active'))
{
$('.nav-tabs li:last').find('a').trigger('click');
}
else
{
}
}
else { }
}
});
</script>
</body>
</html>

Alert User field that is blank is required

Problem: I would like to be able to alert the user if a particular field is empty. Here is how the form looks:
When the user enters a zip code and selects search, I would like a pop up to display to alert the user to select a distance and not display the results. If the user enters hospital name and city drop down, I do not want the alert to appear. Only when the zip code is entered and when the search button is selected.
Here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance">
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
and here is the script that alerts when the miles is blank:
function validateForm() {
var x = document.forms["UrgentCareSearch"]["distance"].value;
if (x == "" || x=="null") {
alert("Please select distance");
return false;
}
UPDATE
I have done the following and it still does not work the way I want to (which is to show the alert when the search button is entered and when the user has entered a zip code. Meaning once the user has entered a zip code and click on the search button to populate the results, the alert will appear notifying to select the miles and the results will not show until user has entered how many miles and click search again):
function validateForm() {
var x = document.forms["UrgentCareSearch"]["miles"].value;
var $zip = $('#zip');
if ((x == "" && $zip != "") ||(x=="null" && $zip != "")) {
alert("Please select distance");
return false;
}
and this is what I when I used required:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return checkTextField()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option value=""></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
adding required to each of the input or select elements would prevent the form from being submitted if they are left blank
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" required /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" required>
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
Or there can jquery touch look at this
first give your form an id lets say myform
$(document).ready(function()
{
$('#myform').submit(function()
{
var name = $("#hospital").val();
var name = $("#city").val();
if(name == "" || name == " ")
{
alert("Please enter name");
return false;
}
if(city == "" || city== " ")
{
alert("Please enter city");
return false;
}
//Just like this and at the end when you are satisfied
$(this).submit();
});
});
From what I understand by your problem statement, you can do the following in your validation function.
function validateForm() {
var miles = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if (zip && !miles) {
event.preventDefault(); // This will prevent the form submit
alert("Please enter the Miles.");
return false; // Does't submit the form (for IE)
}
}
Also, when calling the function, just call the function directly.
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="validateForm();">

Issue with jQuery validate not working against element

I am having an issue using jQuery validate against a form in a current project.
I am sure it is a typo I am missing or something small, but can't sem to figure out why it is occurring.
The error I am getting in the console debugger is: Object doesn't support property or method 'validate'
The bundle configuration file:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Scripts/ContactForm.js"));
The code snippets are below:
<form action="#Url.Action("UpdateContactInformation", "ContactController")" method="post" role="form" class="form-horizontal" id="contactForm">
<input type='hidden' name='csrfmiddlewaretoken' value='brGfMU16YyyG2QEcpLqhb3Zh8AvkYkJt' />
<!-- First Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">First Name</label>
<div class="col-md-4">
<input class="form-control" id="id_firstName" maxlength="75" name="txtFirstName" placeholder="First Name" required="required" title="" type="text" />
</div>
</div>
<!-- Last Name Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Last Name</label>
<div class="col-md-4">
<input class="form-control" id="id_lastName" maxlength="75" name="txtlastName" placeholder="Last Name" required="required" title="" type="text" />
</div>
</div>
<!-- Title Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Title</label>
<div class="col-md-4">
<input class="form-control" id="id_title" maxlength="75" name="txtTitle" placeholder="Title" required="required" title="" type="text" />
</div>
</div>
<!-- Address Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Address</label>
<div class="col-md-4">
<input class="form-control" id="id_address" maxlength="75" name="txtAddress" placeholder="Address" required="required" title="" type="text" />
</div>
</div>
<!-- City Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">City</label>
<div class="col-md-4">
<input class="form-control" id="id_city" maxlength="75" name="txtCity" placeholder="City" required="required" title="" type="text" />
</div>
</div>
<!-- State Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">State</label>
<div class="col-md-4">
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuStates" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Select State
<span class="caret"></span>
</button>
<ul class="dropdown-menu" id="statesDropDownMenu" aria-labelledby="dropdownMenuStates">
</ul>
</div>
</div>
</div>
<!-- Zip Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">ZipCode</label>
<div class="col-md-4">
<input class="form-control" id="id_zipCode" maxlength="75" name="txtZipCode" placeholder="ZipCode" required="required" title="" type="number" />
</div>
</div>
<!-- Email Primary Form Field-->
<div class="form-group required">
<label class="col-md-2 control-label">Email Primary</label>
<div class="col-md-4">
<input class="form-control customEmail" id="id_emailPrimary" maxlength="75" name="txtEmailPrimay" placeholder="Email Primary" required="required" />
</div>
</div>
<!-- Email Secondary (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailSecond" maxlength="75" name="txtEmailSecond" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<!-- Email Third (optional) Form Field-->
<div class="form-group">
<label class="col-md-2 control-label">Email (Optional)</label>
<div class="col-md-4">
<input class="form-control" id="id_emailThird" maxlength="75" name="txtEmailThird" placeholder="Email (Optional)" title="Email (Optional)" type="email" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">
<span class="glyphicon glyphicon-user"></span> Submit Contact Info
</button>
</div>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval");
#Scripts.Render("~/bundles/custom"); //contains the file I am trying to add $.validate.AddMethod() to
Here is the code for Contact.js
$.validator.addMethod(
"customEmail",
function (value, element) {
var re = new RegExp("/^#{0,2}\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*#{0,2}​‌‌​​$/");
return this.optional(element) || re.test(value);
},
"Please enter a valid email address."
);
$(document).ready(function () {
console.log("Were here.........");
// populateStatesDropDown();
$('#contactForm').validate({ // initialize the plugin
rules: {
txtZipCode: {
required: true,
numeric: true
},
txtEmailPrimay: {
required: true,
customEmail:true
},
txtEmailSecond:{
required:false,
customEmail:true,
},
txtEmailThird: {
required: false,
customEmail:true
}
}
});
populateStatesList();
});
function populateStatesList() {
var url = "Contact/GetStates"; // Don't hard code your url's!
//$("#province_dll").change(function () {
var $statesDropDownMenu = $("#statesDropDownMenu"); // Use $(this) so you don't traverse the DOM again
var listItems = '';
$.getJSON(url, function (response) {
$statesDropDownMenu.empty(); // remove any existing options
console.log(response);
$.each(response, function (index, item) {
console.log("Now - " + item);
listItems += "<li>" + item + "</li>";
});
$statesDropDownMenu.html(listItems);
});
//});
}
You have an extra comma.
txtEmailSecond:{
required:false,
customEmail:true, // Here
},

Simplify angular controller posting to Firebase using AngularFire

I'm new to angular but picking it up quickly. I have this controller that works, based on demo code ive hacked together, but there has to be an easier cleaner way to get all the fields and post so if i want to add a new field i dont need to keep adding it in the various locations.
Heres the controller:
'use strict';
angular.module('goskirmishApp').controller('addEvent', function ($scope, fbutil, $timeout) {
// synchronize a read-only, synchronized array of messages, limit to most recent 10
$scope.messages = fbutil.syncArray('messages', {limit: 10});
// display any errors
$scope.messages.$loaded().catch(alert);
// provide a method for adding a message
$scope.addMessage = function(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink) {
if( newEventName ) {
// push a message to the end of the array
$scope.messages.$add({
eventName: newEventName,
eventType: newEventType,
startDate: newStartDate,
startTime: newStartTime,
endDate: newEndDate,
endTime: newEndTime,
eventDescription: newEventDescription,
address: newAddress,
postcode: newPostcode,
ticketInformation: newTicketInformation,
bookLink: newBookLink
})
// display any errors
.catch(alert);
}
};
function alert(msg) {
$scope.err = msg;
$timeout(function() {
$scope.err = null;
}, 5000);
}
});
And the view:
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="newEventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="newEventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newStartDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newStartTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newEndDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newEndTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="newEventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="newAddress">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="newPostcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="newTicketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="newBookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink,newLat,newLong,newApproved);newEventName = null;newEventType = null;newStartDate = null;newStartTime = null;newEndDate = null;newEndTime = null;newEventDescription = null;newAddress = null;newPostcode = null;newTicketInformation = null;newBookLink = null;">Add Event</button>
</form>
Help is greatly appreciated!
Define all your input in a object that you will be directly send send to firebase
For example init in your controller this :
$scope.form = {};
After in your template just define your input as 'form attributes'.
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="form.eventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="form.eventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.startDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.startTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.endDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.endTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="form.eventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="form.address">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="form.postcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="form.ticketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="form.bookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage()">Add Event</button>
</form>
and directly in your addMessage function
$scope.addMessage = function() {
if( $scope.form.eventName ) {
// push a message to the end of the array
$scope.messages.$add($scope.form)
// display any errors
.catch(alert);
//Reset your form
$scope.form = {};
}
};

Categories

Resources