I would like to have a form (injected via ajax) that has multiple validations. Something like this:
<div data-form> <!-- Already on the page -->
<!-- Coming from API -->
<form>
<input type="number" data-input-decimal>
<input type="number" data-input-integer>
<input type="submit">
</form>
</div>
And this is my jQuery:
var $DATA_INPUT_DECIMAL = $('[data-input-decimal]');
var $DATA_INPUT_INTEGER = $('[data-input-integer]');
var $FORM = $('[data-form]');
$FORM.on('keydown', $DATA_INPUT_DECIMAL, function(e) {
console.log('banana');
// This is the validation for the input with decimal
}
$FORM.on('keydown', $DATA_INPUT_INTEGER, function(e) {
console.log('apple');
// This is the validation for the input with ONLY NUMBERS (0-9)
}
The weird part is when I test on the browser, both of these functions are being called when I keydown any of the inputs inside the form. How do I set up different validations properly in this situation?
Thanks in advance!
You need simple delegation:
$('[data-form]').on('keydown', 'input', function(e) {
if ($(this).is('[data-input-decimal]')) {
console.log('decimal');
} else if ($(this).is('[data-input-integer]')) {
console.log('integer');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div data-form>
<!-- Already on the page -->
<!-- Coming from API -->
<form>
<input type="number" data-input-decimal>
<input type="number" data-input-integer>
<input type="submit">
</form>
</div>
Related
I have an html page which has around six different forms with different somewhat unrelated fields in each form. What I'm trying to do is create a single jquery or javascript function to handle all the Fetch() on form submit without knowing the form ID (which is most of what I found in tutorials online). Right now I'm just trying to get the form data to display in an alert, but the alert is always blank (no form data being passed?).
My code for what I think should capture any form submit and display the form data:
<script>
$(document).ready(function() {
$("form").on("submit", function(e) {
console.log("CCCCCCC in script CCCCCCCCCc")
e.preventDefault();
var dataString = $(this).serialize();
alert(dataString);
return false;
});
});
</script>
I have a couple of these type of forms (took out bootstrap class info for ease of reading:
<form>
<div>
<div>
<label for="thing1">Choose:</label>
<select id="thing1" name="thing1">
<option value="XXX">XXX</option>
<option value="YYY">YYY</option>
</select>
</div>
<div>
<label for="inputtext">Command</label>
<input type="text" id="inputtext" name="thing2">
</div>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
How can I get any of the form data into the alert box? Ideally later I will use fetch() after I massage the input string.
The form doesn't have any serializable data.
A form control's data comes from a combination of its name and value but none of your form controls have name attributes.
As #Quentin suggested, you need to give a name to select and input elements, in order to get their values.
For instance:
$('form').submit(function(e) {
e.preventDefault();
var el_1 = this.thing1;
var el_2 = this.inputtext;
alert(el_1.value + ', ' + el_2.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<div>
<div>
<label for="thing1">Choose:</label>
<select id="thing1" name="thing1">
<option value="XXX">XXX</option>
<option value="YYY">YYY</option>
</select>
</div>
<div>
<label for="inputtext">Command</label>
<input type="text" id="inputtext" name="inputtext">
</div>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
In HTML5, when I make a text box like below, and press the submit button.
<input type='number' name ='search_size' id ='search_size' class="" value="" min="0" max="100" >
When the value doesn't meet the min, max value, it will not proceed. However,
My button that handles the text box is made of JQuery. When I type nothing, and click, it processes it. When I type the value over 100, it also processes it. (There are other values from other tags and etc.)
Is there something I can add to JQuery so that it will check the condition or requirement in the text box?
I want to show the JQuery code here, but it is pretty long. Some of it looks like the below.
$("#search_submit").off("click").on("click", function(event_receiver){
$("#loading").css('z-index',-1);
$("#loading_search").css('top',$("#dialog_data_search").position().top + ($("#dialog_data_search").height()*0.7) );
$("#loading_search").show();
var search_data;
var request_obj = {
"baseDN" : $("#search_base_dn").val()
,"filter":$("#search_filter").val()
,"attribute":$("#search_attribute").val()
,"sortAsc":true
,"scope":$(":radio[name='search_scope']:checked").val()
,"size":$("#search_size").val()}; //<-- this guy!!
$.ajax({
url:"/browser/ajaxGetSearchData"
,dataType:"json"
,data:request_obj
,async:true
,type:"post"
,success:function(return_data){
if(return_data.success){
search_data = return_data.result;
}else{
alert(return_data.message);
}
}
you can add a validate function inside the jquery click function of yours. in that validate function the value of the input field must be validated. if it exceeds 100 it should return false
Instead of the <button>'s click event, you want to hook on the <form>'s submit one.
The click event will fire even though the form is invalid, while the submit one will first perform the validation:
document.getElementById('btn').onclick = e => console.log('btn has been clicked');
document.getElementById('form').onsubmit = e => console.log('form has been submitted');
<!-- an always invalid form... -->
<form id="form">
<input name="foo" maxlength="0" required>
<button id='btn'>bar</button>
</form>
Use validation bootstrap like this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form>
<div class="form-group">
<label for="number">Number</label>
<input type="number" class="form-control" name ='search_size' id ='search_size' value="0" min="0" max="100" required>
</div>
<button class="btn" type="submit">submit</button>
</form>
When I use default HTML validation it shows the default error messages which is not I want to show to my clients. I need to customize the message and give different massages for each validations such as min, max, type and require. For Example:
The field is required, The value does not match
Refer the tradition HTML Code:
<input type="text" required>
I want something like this:
<input type="text" validation="required|my_message,min:5|my_message">
It's totally possible with custom libraries in jQuery which I would suggest - https://github.com/aslamanver/abvalidate
Custom Message - jQuery Form Validation - abValidate.js
ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name"
Use this library by adding these CDNs
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- abValidate Library -->
<script type="text/javascript" src="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.min.js">
<link rel="stylesheet" href="https://raw.githubusercontent.com/aslamanver/abvalidate/master/abValidate.css">
Initialize the library
$(document).ready(function () {
//.ab-form is your form class
$(".ab-form").abValidate();
});
There you go, now you can use your custom validation using jQuery abValidate library
<form class="ab-form" action="your_action_url">
<!-- Input and error message should be in a div class -->
<div class="my-form-group">
<input type="text" ab-validation="required|Hey dude you missed that,min:5| No no you want to type more" name="name" class="ab-validation-i" />
<div class="error"></div>
</div><br>
<div class="my-form-group">
<input type="submit" name="submit" value="Submit">
</div>
</form>
Try this one, its better and tested:
HTML:
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
JAVASCRIPT:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/
I have a form that I wanted be nested, but it is not possible since HTML can't accept nested form. Is there a way I can manually invoke the submit(triggers the validation, e.g. required) on first form on AngularJS?
Here's how the code looks like:
<div ng-conroller="ContactController">
<form ng-submit="saveHeaderAndDetail()">
<label for="Description">Description</label>
<input type="text" ng-model="Description" required/>
<input type="text" style="visibility:hidden" />
</form>
<form ng-submit="addToDetail()">
...
</form>
<input type="button"
ng-click="what code could trigger the first form's submit?"/>
</div>
Btw, both forms are under one controller if that helps
Try creating a directive that catches an event:
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.triggerSubmit = function() {
$scope.$broadcast('myEvent');
console.log('broad');
};
$scope.onSubmitted = function() {
alert('submitted!');
};
}
app.directive('submitOn', function() {
return {
link: function(scope, elm, attrs) {
scope.$on(attrs.submitOn, function() {
//We can't trigger submit immediately, or we get $digest already in progress error :-[ (because ng-submit does an $apply of its own)
setTimeout(function() {
elm.trigger('submit');
});
});
}
};
});
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">
<form submit-on="myEvent" ng-submit="onSubmitted()">
Form...
</form>
<hr />
<a class="btn" ng-click="triggerSubmit()">Submit</a>
</div>
Original source:
http://jsfiddle.net/unWF3/
I've answered a similar question here AngularJS - How to trigger submit in a nested form
Basically, you can trigger validation by firing $validate event
isFormValid = function($scope, ngForm) {
$scope.$broadcast('$validate');
if(! ngForm.$invalid) {
return true;
}
For working code example & a small utility method which is helpful in showing validation messages, see answer in the above link.
You can have nested forms with ng-form directive. It will be like:
<form name="accountForm">
<div data-ng-form="detailsForm">
<input required name="name" data-ng-model="name">
</div>
<div data-ng-form="contactsForm">
<input required name="address" data-ng-model="address">
</div>
<button type="submit">Save</button>
</form>
That way when submit will be triggered for the accountForm it will validate nested ng-forms also.
There's an easier way to do that, You can give a name for each form that you have in your app, then you'll be able to send the entire angular object of the form that you want to trigger or do whatever you want with it. Example:
<div ng-conroller="ContactController">
<form name="myFirstForm" ng-submit="saveHeaderAndDetail()">
<label for="Description">Description</label>
<input type="text" ng-model="Description" required/>
<input type="text" style="visibility:hidden" />
</form>
<form name="mySecondForm" ng-submit="addToDetail()">
...
</form>
<input type="button"
ng-click="saveHeaderAndDetail(myFirstForm)"/>
</div>
Then in your function
saveHeaderAndDetail (myFirstForm) {
myFirstForm.$submitted = true
...
}
We can always submit a form directly using the submit
() function from javascript.
document.getElementById("myform").submit()
In this way, we can validate the form using angularjs first and if the form is valid then submit it using the submit method.
I am using javascript validation for my input box from javascript-coder and it works fine on my non-ajax pages but when I use ajax to POST inputs the script runs through without stopping even if validation fails. I tried an example from here but when I tried the suggestion the validation didn't work at all. In my ajax script I can get everything to work with jquery validation by simply putting this in before posting data:
var frm = $(this).closest('form');
if($(frm).valid()){
But I really want to stick with this validation library so I am hoping someone in the community more familiar javascript and maybe even this validation library can help me find an equivalent because I haven't been able to find anything in all the documentation that allows you to test if validation failed or not before moving my ajax script forward.
My form:
<form method="post" name="send_message_frm" id="send_message_frm">
<div style="margin-top:20px;"></div>
<fieldset>
<div class="clear"></div>
<div style="margin-top:20px;"></div>
<label>Product Group Name:</label>
<input name="desc" class="text-input medium3-input required" type="text" id="desc" value="">
<div style="color:red;" id='send_message_frm_desc_errorloc' ></div>
<div style="margin-top:20px;"></div>
</fieldset>
<input name="user" class="text-input medium3-input" type="hidden" id="user" value="<?php echo $myid ; ?>">
<div style="margin-top:20px;"></div>
<input type="submit" id="send-message" name="submit" value="Send" class='button' />
<div style="margin-top:20px;"></div>
</form>
<script type="text/javascript">
var frmvalidator = new Validator("send_message_frm");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("desc","alnum","Only numbers and letters are allowed");
frmvalidator.addValidation("desc","req","Please enter a description");
</script>
My Ajax script:
<script type="text/javascript">
$(document).ready(function(){
//Validate form....what can I put here to test if validation is completed properly????
//onclick handler send message btn
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"productgroup_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>
After reviewing the validation script, I discovered (as suspected) that it attaches the validation method to the form's OnSubmit event handler, which sounds about right...
this.formobj.onsubmit = form_submit_handler;
But... it also attaches itself to the form object:
this.formobj.validatorobj = this;
which has a method that you can call to validate your form:
if (!this.runAddnlValidations())
To run the validations, it looks like you can just do something like:
if(!document.forms[0].validatorobj.runAddnlValidations()) return;