How to validate some fields and selects on ng-click AngularJS - javascript

I have a list of some input fields and few select options, so I want them be required on ng-click and raise a message just over the particular required item in form of PopupMenu or kind of that, or what ever the suitable way to show require warning just over the field
Hierarchy in my case:
<form>
<input required
<input required
location form for multiple records (not form tag)
contact form for multiple contacts (not form tag)
submit button to post (input required), all locations and all contacts.
</form>
My Form:
<div class="form-inline">
<div class="form-group">
<input type="text" placeholder="Legal Name" ng-model="companyForm.legalName" required/>
</div>
<div class="form-group">
<input type="text" placeholder="EIN" ng-model="companyForm.ein"/>
</div>
<div class="form-group" id="selectFormationDiv">
<select id="formationListId"></select>
</div>
<div class="form-group">
<input type="checkbox" style="margin-top: 5px;" ng-model="companyForm.internal"/> <b>Internal</b>
</div>
</div>
Note this is not form, and not be called on ng-submit.
My Output:
My Desired output:
Please guide me through how do I code to get my desired output. Thanks

angular.module('app', [])
.error {
color: red;
}
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app'>
<form name="form" class="css-form" novalidate>
<input type='text' ng-model='temp1' required name='temp1' />
<span ng-show="form.temp1.$error.required && form.$submitted" class='error'>
field1 is required
</span>
<br>
<input type='text' ng-model='temp2' required name='temp2' />
<span ng-show="form.temp2.$error.required && form.$submitted" class='error'>
field2 is required
</span>
<br>
<input type="submit" value="Save" />
</form>
<hr>
<!--Solution without `<form>` tag: -->
<input type='text' ng-model='temp3' name='temp3' />
<span ng-show="!temp3 && $submitted" class='error'>field3 is required</span>
<br>
<input type='text' ng-model='temp4' name='temp4' />
<span ng-show="!temp4 && $submitted" class='error'>field4 is required</span>
<br>
<input type="button" ng-click='$submitted=true' value="Save" />
</div>

Related

ANGULAR - Disable submit button if form value not changed

i have form for selected date. how to disable the submit button if nothing changed in date form?
my html code
<div class="col-xs-6">
<label><i class="far fa-calendar-alt"></i> Start <span class="text-danger">*</span></label>
<input id="startTrip1" name="NgbDate" data-provide="datepicker" ngbDatepicker #d="ngbDatepicker" [markDisabled]="markDisabled" [minDate]="minDates" type="text" class="form-control form-flat" [(ngModel)]="ad.start_date" (dateSelect)="onDateSelect($event, ad)" (blur)="validateInput()" (click)="d.toggle()" [ngModelOptions]="{standalone: true}" [disabled]="form.controls.tripduration.hasError('required')" >
<div class="text-danger" *ngIf="(ad.start_date == '' || ad.start_date == undefined) && ngForm.submitted">
* This field is required
</div>
<div class="text-danger" *ngIf="form.controls.tripduration.hasError('required')">
* Fill the durations first
</div>
</div>
//submit button
<button class="col-xs-12 text-center text-strong pointer custom-trip-btn" (click)="publishTrip()">
<button class="custom-trip-btn">SUBMIT</button>
If you used below code, the button only enabled if user changed value in the form
[disabled]="!(accountForm.valid && accountForm.dirty)"
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
<button type="submit" [disabled]="!profileForm.dirty">Submit</button>
Read more about it here
Hope this works!
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
<button [disabled]="!(profileForm.valid ||!profileForm['isDirty']())"
class="btn btn-primary">Submit</button>
Check some what same question here
Stackblitz-example of some old problem of mine
for the above you need to use RxReactiveFormsModule RxReactive npm

how to get a dynamic form id generated by jsp in jquery

How to get a formId that is generated by using a jsp using jquery?
<c:url var="updateSubUserDetails" value="/employer/recruiters/updateSubUserDetails"/>
<form id="updateform${subUser.employerId}" action="${updateSubUserDetails}" method="post" >
<div class="modal-body">
<input type="hidden" name="subUserId" value="${subUser.employerId}"/>
<div class="form-group">
<input type="text" id="subUserName${subUser.employerId}" name="subUserName" class="form-control " value="${subUser.firstName}" placeholder="Edit Sub User Name"/>
</div>
<div class="form-group">
<input type="text" id="subUserEmail${subUser.employerId}" name="subUserEmail" class="form-control " value="${subUser.emailId}" onchange="checkMail(${subUser.employerId})" placeholder="Edit Email"/>
</div>
<span id="avialabilityMessage${subUser.employerId}"></span>
<div class="form-group">
<input type="text" id="subUserMobile${subUser.employerId}" name="subUserMobile" class="form-control " value="${subUser.mobileNumber}"placeholder="Edit Contact No"/>
</div>
<sec:csrfInput/>
<div class="modal-footer">
<input type="button" id="muEditButtonID" onclick="updateSubUserDetails(${subUser.employerId})" class="btn btn-warning btn-lg glyphicon glyphicon-ok-sign" value="Update"> 
</div>
</div>
</form>
How to get above dynamically generated form id in javascript jquery? Please assist me.
//if you sure there is only one form
document.forms[0]
//else
document.querySelector('[id^="updateform"]')
so, if you want to get id just add .id
//if you sure there is only one form
document.forms[0].id
//else
document.querySelector('[id^="updateform"]').id

displaying error messages below the input form

I would like to know how can i display an error message below the input field using angular js. If the field is empty i want to display "This field is required". Also how to check if the field name starts with alphanumeric values like (\?/%*:|"<.>) i need to display the error "The field name should not start with alphanumeric values" below that input field. // code goes here
<div ng-controller="ModalController">
<form novalidate name="inputForm" class="form-horizontal">
<div class="row">
<div class="col-md-12">
<cp-input name="username" ng-model="user.name"
label="{{'formlabels.reponame' | translate}}" required="true"
error-state="right">
</cp-input>
</div>
</div>
<div style="color:red" ng-show="inputForm.username.$error.required">First name is required</div><br>
</form>
<!-- Show Confirm -->
<button type="button" class="btn btn-primary" data-dismiss="modal"
data-ng-click="submitData()">Add</button>
</div>
It would be a good idea to use ngMessages directive and ngPattern - take a look at the doc link with example
<form name="myForm">
<label>
Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="5"
ng-maxlength="20"
ng-pattern="^[^\w+$]"
required />
</label>
<pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
<div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
</div>
</form>
ref https://docs.angularjs.org/api/ngMessages/directive/ngMessages
ng-messages will help you..Try this
<input ng-model="typeText" id="Sample" name="Sample" type="text" ng-pattern="^$|^[A-Za-z0-9]+" required/>
or ng-pattern="/^[a-zA-Z\s]*$/"
<div ng-messages="formname.Sample.$error">
<div ng-message="pattern">only characters are allowed</div>
<div ng-message="required">field required</div>
</div>

Detect the name of required field and not validated when submit a form

I create a form in html5 like this example :
<form action="/my/url/insert.php" method="POST">
<div class="row">
name <input name="name" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
$('form').submit(function(){
console.log('test');
});
</script>
The problem :
I want to detect the name of the required field that are not validated when submiting and logging it.
for example : if I don't fill the input "album" when submit i detect it before the message "a field is required..."
is there a way to do this ?
thank you.
Here you go.. Loop through each input:required field and get its name with .attr.
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
console.log($(this).attr('name'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Updated
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
if($(this).val()==""){ //check if its empty
console.log($(this).attr('name'));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Assuming that only required will be the property for validation, above condition will hold good and yea, by default when you say required, browser will have its validation suppressing validation written by you. If you want your validation to work, add novalidate to form as said in one of the comments above..
Select them by property required:
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
console.log($(this).attr("name"));
});
});
});
To do a simple required check on your own make a simple "not empty" condition. But for this, your form need the novalidate class, otherwise submit callback will not be triggered and nothing ever happens.
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
if( $(this).val() != "" )
console.log($(this).attr("name"));
});
});
});
Full example here: https://jsfiddle.net/vvdh66rb/
You can also do like this:
<form action="/my/url/insert.php" method="POST" onSubmit="return myFunction()">
<div class="row">
<!--I am only giving id to one to show an exmaple you can give to differnt-->
name <input name="name" id="some" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
function myFunction() {
var x = document.getElementById('some').value;
if (x == "" || x == null) {
alert('sadsd');
return false;
//You can give anything else than alert
}
}

Multiple products in one form

I would like to add a functionality in my form, in which a user can add as many entries before hitting submit button, like a 'add to cart' functionality, show the added entries in same page, in a separate div with submit button then save those multiple entry in database using that submit button(in a separate div that shows added entry).
So far my form allows only entries on per submit bases, meaning is if the user wants to add another entry, he/she has to go back to the form and add and click to submit again.
<form method="POST" name="myForm" action="saveto.php">
<label> Speed Rating:</label>
<select name="speed_rating" required class="form-control" id="speed_rating" ></select>
<div class="form-group col-sm-8">
<label> Description:</label>
<select name="description" required class="form-control" id="description" >
</select>
</div>
<div class="form-group col-sm-4">
<label> Load Index:</label>
<select name="load_index" required class="form-control" id="load_index" >
</select>
</div>
<div class="form-group col-sm-6">
<label> Vendor:</label>
<select name="vendor" required class="form-control" id="vendor" >
</select>
<div class="note"> Recommended Vendor : <span id="recomvend"> </span> </div>
</div>
<div class="form-group col-sm-6">
<label> Quantity:</label>
<input type="text" required name="qty" class="form-control" id="qty"></div>
<div style="clear:both"> </div>
<input type="submit" name="submit" class="btn btn-primary smp" value="Submit">
<button id="clear" type="button" class="btn btn-primary smp smp2" > Reset </button>
</div>
<input type="submit" value="submit" name="submit">
</form>
How would you achieved this? My saveto.php is just a normal script that will process the submitted data to database, one entry in a per submit bases.
I created this jsfiddle https://jsfiddle.net/jy6vh4rp/31/
If that's what you are looking for then you should add this to your front end:
<form action="validate.php" method="post">
<div style="padding: 30px 0; text-align: center;">
<button type="button" onclick="createDOM()">Add</button>
<input type="submit" value="submit" name="submit" />
</div>
<div class="productsContainer"></div>
</form>
<script>
$(document).ready(function() {
id = 0;
createDOM = function() {
$(".productsContainer").append('<input type="text" id="' + id + '" name="products[]" value="' + id + '" />');
id++;
};
});
</script>
And this to your validation backend :
foreach($_POST['products'] as $prodInput){
$product = filter_var($prodInput,FILTER_SANITIZE_NUMBER_INT);
if( is_numeric($product) ){
echo $product;
}
}

Categories