Iam trying to validate my form step by step on clicking a button called 'next'.
Is there a way to fire a custom event to trigger partial form validation?
Something like that:
<input type="text" id="age-id" name="age"
ng-model-options="{updateOn: 'ValidateStepOne'}"
min="18"
max="99"
ng-model="data.age"
>
Triggering the event onclick at a button:
$scope.validate = function() {
$rootScope.$broadcast('ValidateStepOne');
};
Any help would be kindly appreciated.
Kind regards
OliverKK
I was separating the huge form into sub forms(thanks to #fiskers7), which is pretty handy.
The validation takes place by using a custom trigger on clicking at the
next button to validate the current step.
The required validator and other used validators will be executed when the custom submit event is fired.
<form id="form1" ng-submit="validate(1)" ng-model-options="{ updateOn: 'submit' }" novalidate>
<input type="text" ng-model="name" required>
<span ng-show="form1.$submitted && form1['name'].$error.required">Name is required!</span>
<input type="submit" value="next">
</form>
<form id="form2" ng-submit="validate(2)" ng-model-options="{ updateOn: 'submit' }" novalidate>
<input type="text" ng-model="surename" required>
<span ng-show="form2.$submitted && form1['surename'].$error.required">Name is required!</span>
<input type="submit" value="next">
</form>
The validation function submit within the controller looks like this:
$scope.validate = function(num) {
$scope['form' + num].$setSubmitted(true);
if (!$scope['form' + num].$valid) {
$scope.scrollToTop();
} else if (num < $scope.maxSteps) {
$scope.next(num + 1);
} else {
$scope.submit();
}
}
See the AngularJS Documentation for more details:
https://docs.angularjs.org/guide/forms
Kind regards
OliverKK
You can separate your form into several pieces that use ng-if to decide whether to show them or not.
<form action="" name="myForm">
<div ng-if="step == 1">
<input type="text" required="true" name="input1" ng-model="inputVal1"/>
</div>
<div ng-if="step == 2">
<input type="text" required="true" name="input2" ng-model="inputVal2"/>
</div>
</form>
see example.
Related
I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>
I'm wondering if there's a way to force a check for the required inputs on a form before submitting it programmatically using pure Javascript:
<form method="post" action="myController.php" id="myForm">
<input type="text" id="input1" required>
<input type="text" id="input2" required>
<input type="text" id="input3" required>
<input type="submit" onClick="return checkForm(event)" value="Save">
</form>
My Javascript file:
function checkForm(e) {
e.preventDefault();
// Some other stuff
/*Prevalidate required inputs here*/
document.getElementById('myForm').submit();
}
I'm wondering if there's something like:
if(document.getElementById('myForm').valid()) {
document.getElementById('myForm').submit()
}
Where the required inputs are checked just before submitting the form without the need to verify one by one directly by code.
There is the form.onSubmit event
But if you are using HTML 5, you can use input.pattern with a regular expression; submission will be blocked if the input doesn't pass the check and the input element will (on many browsers) get a red border around it.
If you need to do something custom on submit you can trigger validation via form.reportValidity() and get back a boolean indicating whether all inputs have satisfied their constraints.
You can also listen for invalid events that will get fired for each invalid input during validation if you want to do something to flag them in the UI:
function onInvalid (e) {
e.target.classList.add('invalid');
}
const form = document.querySelector('form');
document.querySelectorAll('input').forEach(input => {
input.addEventListener('invalid', onInvalid);
});
form.addEventListener('submit', (e) => {
e.preventDefault();
const valid = form.reportValidity();
})
.invalid {
border: 4px solid red;
}
<form>
<input name="test1" required />
<input name="test2" required />
<input name="test3" required />
<input type="submit" />
</form>
Take adventage of Form attribute onsumbit to submit the form if the value returned from the function checkForm which returns boolean value if all fields are filled and not empty dynamically.
function checkForm(e) {
let valid = true;
inputs = document.querySelectorAll('[type="text"]')
for(input of inputs){
if(input.value.trim()==''){
valid = false;
break;
}
}
return valid;
}
<form method="post" id="myForm" action='test.php' onsubmit="return checkForm(this)">
<input type="text" id="input1" required>
<input type="text" id="input2" required>
<input type="text" id="input3" required>
<input type="submit" value="Save">
</form>
I have a form. In which I have input fields and I am doing some validation based on input. Also, there is a submit button which enables only if form is valid.
In this form I am enabling/disabling input field in one of the flow.
Initially, when the fields are enable and empty, create button is disabled. After i disable and enable the fields, create button becomes enabled. Although input fields are still empty.
More over button which is enabling/disabling this part is outside of this form.
Here is my code
`
<form method="post" novalidate id="example-widgets-form" name="mdnsCtrl.createSubDomainForm" valdr-type="SubDomain">
<div>
<label>Domain Name</label>
<input required type="text" name="subDomainName" placeholder="Domain Name" ng-model="mdnsCtrl.newDomain.name">
</div>
<div>
<label>Description</label>
<input type="text" name="subDomainDescription" placeholder="Description (Optional)" ng-model="mdnsCtrl.newDomain.description">
</div>
<button type="button" aria-label="Create" ng-click="mdnsCtrl.createDomain();"
ng-disabled="mdnsCtrl.createSubDomainForm.$invalid">
<span class="ng-scope">Create</span>
</button>
</div>
</form>
Tried few things like using $setUntouched() and $setPristine(). But nothing is working. Any help will be appreciated.
Adding a codepen example for this: code
Much Thanks.
`
Its not good practice to mix Angular with jQuery. Please read this great post: “Thinking in AngularJS” if I have a jQuery background?
You can easily achieve requested behavior by using ng-disabled="mdnsCtrl.formDisabled"
JS
var ctrl = this;
ctrl.formDisabled = false;
this.disable = function(){
ctrl.formDisabled = true;
};
this.enable = function(){
ctrl.formDisabled = false;
};
HTML
<div>
<label>Domain Name</label>
<input class="input-field" required type="text" name="subDomainName" placeholder="Domain Name"
ng-disabled="mdnsCtrl.formDisabled"
ng-model="mdnsCtrl.name" >
</div>
<div>
<label>Description</label>
<input class="input-field" type="text" name="subDomainDescription"
ng-disabled="mdnsCtrl.formDisabled"
placeholder="Description (Optional)" ng-model="mdnsCtrl.description">
</div>
Fixed Demo Codepen
I think you missed required attribute for Description input..
<input type="text" name="subDomainDescription" required ng-model="mdnsCtrl.newDomain.description">
I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.
The code appears to be hooked up (like this)
jQuery("#contactForm").validationEngine();
because it will validate and raise an error bubble if:
you tab out of required field without any input
you type at least one character into a field that requires more and then click the submit button
But it will not validate and raise an error bubble if you do nothing at all except click the submit button. In that case, it just submits. Once you click in the field or enter anything at all, it seems to work.
What can I be looking for that I've mis-configured?
The HTML:
<form class = "contactform" id = "contactForm">
<fieldset>
<div class="contactform-name contactform-field">
<label class="contactform-label" for="contactform-name">Name:
<br>
</label>
<input class="validate[required,minSize[8]] contactform-input" type="text" id="contactform-name" name="name" />
</div>
<div class="contactform-email contactform-field">
<label class="contactform-label" for="contactform-email">Email Address:<br></label>
<input value class="validate[required,custom[email]] contactform-input" type="email" id="contactform-email" name="contactform-email" />
</div>
<div class="contactform-text contactform-field">
<label class="contactform-label" for="contactform-text">Message:
<br>
</label>
<textarea class="validate[required,minSize[12]]contactform-input" name="text" id="contactform-text" > </textarea>
</div>
<input class="contactform-button" type="submit" name="submit" value="Send" />
</fieldset>
</form>
The JavaScript (it's running in Meteor):
Template.Contact.rendered = function () {
jQuery("#contactForm").validationEngine();
}
I've never used this engine, but from the docs I found that 'attach' will attach the validator to form.submit. Can it be as simple as that?
https://github.com/posabsolute/jQuery-Validation-Engine#attach
EDIT:
You can also do stuff to the submit-event (if the tip above won't help).
Something like this (not tested, but should put you in the correct path):
Template.templateName.events({
'submit': function(event) {
// Prevent the submit with preventDefault()
event.preventDefault();
// Do something to check the submit etc.
}
});