AngularJS validation on submit - javascript

I have a register form that I wish to do validation on the moment a user clicks submit. This is what the HTML looks like:
<form ng-submit="RegistrationC.fireReg()" novalidate name="register">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" autocomplete="off" class="form-control" placeholder="First Name" ng-model="RegistrationC.first_name" required name="first_name">
<div class="help-block" ng-messages="register.first_name.$error" ng-show="submitted && register.first_name.$error">
<p ng-message="required">This field is required.</p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 form-group col-md-offset-3">
<button type="submit" class="btn btn-success btn-block" ng-click="submitted=true">Register Now</button>
</div>
</div>
</form>
It is showing the validation message if a username is not typed in, but it still submits. What am I missing?
EDIT 1
//init.js - RegistrationController
reg_list.fireReg = function () {
var url = 'user/register';
api.makeCall(reg_list, url)
.then(function (response) {
reg_list.response = response;
console.warn(response);
$location.path('/user/verify');
})
.catch(function (errorMessage) {
console.log("got an error in initial processing", errorMessage);
event.restoreButton();
});
};
I know there's issues in this function, I will fix them at a later stage.

Submit this form only if it is valid. <whatever_form_name>.$valid
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">

Just add checkpoint whether form is valid or not before submitting form
Try like this
<form ng-submit="register.$valid && RegistrationC.fireReg()" novalidate name="register">

If you want to disable html5(or browser) validator, You have to remove 'required' attribute in your html code
http://www.the-art-of-web.com/html/html5-form-validation/
http://www.w3schools.com/tags/att_input_required.asp

Related

add customized field for bootstrap validation modal

i'm using bootstrap's form validation to validate a form. i wan to add an extra field called discount code. this field should accept only specified codes. when the field is empty it should light green, when the code is right it should light green and when the code is wrong it should light red. how can i do that using the bootstrap form validation?
thats how my form almost looks like
<form class="needs-validation" novalidate>
<div class="form-group">
<div class="col-md-12">
<strong>Enter your name </strong>
<input type="text" name="name" id="name" class="form-control" value="" required minlength="3" />
<div class="invalid-feedback">
Name should be at least 3 characters
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
<script>
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
</script>

JavaScript : Enable button if field is filled is not automatical

function checkValid() {
var cbChecked = $(".fakeRadio").is(":checked"); // check if checked
var hasText = $("#email-download-document").val().length > 0; // check if it has text
$("#document-choice-button").prop("disabled", !cbChecked || !hasText);
}
$(function() {
checkValid(); // run it for the first time
$(".fakeRadio").on("change", checkValid); // bind checkbox
$("#email-download-document").on("change", checkValid) // bind textbox
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument" placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Send to my email' %}" />
</div>
</div>
I would like to get your help because I have a little issue with my simple Javascript part and Chrome Browser.
With Chrome, my button is greyed out until I click outside of the field when this one is filled. I would like to enable my button when the field is automatically filled with email verification thanks to type='email'.
This is an example :
Try with input event instead of change.
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
function checkValid() {
var cbChecked = $(".fakeRadio").is(":checked"); // check if checked
var hasText = $("#email-download-document").val().length > 0; // check if it has text
$("#document-choice-button").prop("disabled", !cbChecked || !hasText);
}
$(function () {
checkValid(); // run it for the first time
$(".fakeRadio").on("input", checkValid); // bind checkbox
$("#email-download-document").on("input", checkValid) // bind textbox
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Fake Radio</label>
<input type="radio" class="fakeRadio" checked>
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument"
placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected"
value="Send to my email"/>
</div>
</div>
Try to use 'input' event instead of 'change' event in your Javascript, to trigger the function when the user is typing into the field.
Have your HTML button by default disabled
<input id="document-choice-button" type="submit" ... disabled="disabled" />
This way, it will load disabled without any javascript.
Then, attach a function to keyup event of your textbox to check if the length of the current text is greater than zero.
$("#email-download-document").keyup(function(){ // triggered at any keystroke
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled"); // enable the field
} else {
$("#document-choice-button").prop("disabled","disabled"); // disable the field
}
});
PS: This will make the button enabled/disabled as you are typing or clearing text from the textfield. If you would like to only disable/re-enable after you have exited the textfield, then you will need to attach the function to the change event
$("#email-download-document").change(function(){ //triggered after leaving textbox
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled");
} else {
$("#document-choice-button").prop("disabled","disabled");
}
});
$("#email-download-document").keyup(function(){
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled");
} else {
$("#document-choice-button").prop("disabled","disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument" placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Send to my email' %}" disabled="disabled" />
</div>
</div>

Form action is not interrupted by "required" inputs

I have the following HTML code.
function document_save_changes(){
if (is_key_dirty == true){
var elm = document.getElementById('set_doc_button');
key_change_warning(elm, 'D');
return;
}
if (document_save_warning('A') == false){
return;
}
collect_nonkey_data();
do_recaptcha();
}
<form id="email_form">
<div id="email_table" class="emltbl inbtop" style="margin:auto;">
<div class="emlrow">
<div class="emlcll">Name:</div>
<div class="emlcll"><input class="email_input" type="text" name="email_1" id="email_1" placeholder="First and last name" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Email:</div>
<div class="emlcll"><input class="email_input" type="email" name="email_2" id="email_2" placeholder="Return email address" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Messg:</div>
<div class="emlcll"><textarea class="email_textarea" name="email_3" id="email_3" placeholder="Message to admin" required autocomplete="off"></textarea></div>
</div>
</div>
<div id="email_recaptcha" class="g-recaptcha" data-sitekey="key goes here"></div>
<div><button id="set_doc_button" type="button" style="padding:0.3em 1em;" disabled="disabled" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button></div>
</form>
My problem is that the "required" INPUT elements are not causing the form submission to fail when the INPUT elements are not filled properly. (For instance, by the type="email" INPUT element which requires special syntax.)
How do I make it so that the "required" INPUTs interrupt the form action if they are not filled in properly? Thanks.
This is because you're not submitting the form. Making a button at the last of type button doesn't make it a submit button. You'll have to specify the type='submit' explicitly to make a button submit the form.
And now to the second part,
If you're trying to submit the form from JS function. The HTML5 validation won't work.
Inshort they are only in action when form is submitted with a button of type submit inside that form. And if you do want to use a button of type button and submit the form with JS, you'll have to check for validation in your JS code.
And in your JS code you can use checkValidity() function on any form to check if it's a valid from or not and then run the other things accordingly
var form = document.getElementById("email_form");
function document_save_changes() {
//Do your things
if (form.checkValidity()) {
form.submit();
} else {
alert("Something worng yet")
}
}
<form id="email_form">
<div id="email_table" class="emltbl inbtop" style="margin:auto;">
<div class="emlrow">
<div class="emlcll">Name:</div>
<div class="emlcll"><input class="email_input" type="text" name="email_1" id="email_1" placeholder="First and last name" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Email:</div>
<div class="emlcll"><input class="email_input" type="email" name="email_2" id="email_2" placeholder="Return email address" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Messg:</div>
<div class="emlcll"><textarea class="email_textarea" name="email_3" id="email_3" placeholder="Message to admin" required autocomplete="off"></textarea></div>
</div>
</div>
<div id="email_recaptcha" class="g-recaptcha" data-sitekey="key goes here"></div>
<div><button id="set_doc_button" type="button" style="padding:0.3em 1em;" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button></div>
</form>
try this one
Use button type='submit' instead of button
<button id="set_doc_button" type="submit" style="padding:0.3em 1em;" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button>
and remove disabled="disabled" after that your form will submit

How to do a Survey Form to be submitted in angularjs

I want to submit a form in angularjs which are like survey, suppose
user will fill the form and submit, I have array of all the questions
of form, I want to update all the questions with the respected answers
by iterating all the questions from array and update each question
individually(why because I only have API to update one question)
This is my form
<ng-form name="participateSurveyForm" novalidate>
<div class="form_fields_survey_audience" ng-repeat="questionlistitem in surveyquestiondata">
<h3 class="">{{questionlistitem.question}}</h3>
<div ng-show="questionlistitem.question_type == 'multiple_choice'">
<div class="radio" ng-repeat="optionofanswers in questionlistitem.options">
<div class="form-group">
<label>
<input type="radio" name="optionforanswer" ng-model="surveydataforparticipate.optionforanswer" ng-value="optionofanswers.option" required checked>{{optionofanswers.option}}
</label>
</div>
</div>
</div>
<div ng-show="questionlistitem.question_type == 'open_text'">
<div class="form-group" >
<textarea class="textAreaMultiligne" name="open_text_field" ng-model="surveydataforparticipate.open_text_field" required placeholder="Answer Here" rows="10" cols="40"></textarea>
</div>
</div>
</div> <!--End Row-->
<div class="row">
<div class="col-lg-12">
<button type="submit" ng-click="participateInSurvey(surveydataforparticipate)" class="btn btn-primary">Complete</button>
</div>
</div><!--row & Submit Button-->
</ng-form>
//Anguar Code
$scope.participateInSurvey = function(surveydataforparticipate){
angular.foreach(surveydataforparticipate, function(value){
$http.put('/api/survey/question/+value._id, surveydataforparticipate).success(function(data){
console.log(data);
});
});
}
not getting values from this surveydataforparticipate function. also
Is it correct that i have put foreach to submit the data using $http?
Thanks for helping.
You can define a function in your controller where the form should go on submit. And, use ng-submit to link that function to your form.
<ng-form name="participateSurveyForm" ng-submit="submitForm ()" novalidate>
In your controller :
$scope.submitForm = function(){
//definition of the function.
//access form data here.
}

How to show success message after validation

I want to valid some fields and I want to show success message $('.alert-success').show(); after user entered all values.
I tried here jsfiddle Now I am able to validate all fields but I don't know how to show success message if all fields are not null.
Html:
<div class="contentContainer">
<div class="alert alert-success hide">Form submitted successfully</div>
<div id="basicInfo">
<div class="toggleContentInnerSec">
<div class="row-fluid">
<div class="span7">
<label>First Name</label> <br>
<p class="hide firstNameErrorMsg error">Please enter first name</p>
<input type="text" name="borrowerBasicDetail.firstName" value="" id="addBorrowers_borrowerBasicDetail_firstName" class="access required" placeholder="Example: 'Sachin' " data-errormsg="firstNameErrorMsg"> <br>
<label>Last Name</label> <br>
<p class="hide lastNameErrorMsg error">Please enter last name</p>
<input type="text" name="borrowerBasicDetail.lastName" value="" id="addBorrowers_borrowerBasicDetail_lastName" class="access required" placeholder="Example: 'Tendulkar' " data-errormsg="lastNameErrorMsg"> <br>
<label>Date Of Birth</label> <br>
<p class="hide birthDayErrorMsg error">Please enter date of birth</p>
<input type="text" name="borrowerBasicDetail.age" value="" id="addBorrowers_borrowerBasicDetail_age" class="access required" placeholder="DD/MM/YYYY" data-errormsg="birthDayErrorMsg"> <br>
</div>
</div>
</div>
</div>
<div class="row-fluid pull-left">
<div class="form-actions">
<a class="btn btn-success btn-large" id="tabOneSubmit">Submit</a>
</div>
</div>
</div>
Script:
submit();
function submit(){
$('#tabOneSubmit').click(function(){
$('.required').each(function(){
var element=$(this);
var elementVal=$(this).val();
var errorMsgId=element.attr('data-errorMsg');
if(elementVal==''){
$('.'+errorMsgId).show();
element.addClass('errorField');
}
else{
$('.'+errorMsgId).hide();
element.removeClass('errorField');
}
});
});
}
Here is the solution, just set a status variable.
submit();
function submit(){
$('#tabOneSubmit').click(function(){
var status=true;
$('.required').each(function(){
var element=$(this);
var elementVal=$(this).val();
var errorMsgId=element.attr('data-errorMsg');
if(elementVal==''){
$('.'+errorMsgId).show();
element.addClass('errorField');
status=false;
}
else{
$('.'+errorMsgId).hide();
element.removeClass('errorField');
}
});
if(status) {
$('.alert-success').show();
}
});
}
Demo
$("#msg").html("Form was submitted");
First, using validator is a good thing but I suggest you check inputs in server side too, because it's easy to hack javascript code.
Secondly you need the encapsulate that your input fields via;
<form method="POST or GET" action="foo.html"> </form>
Then you can use jQuery submit() method to submit via javascript:
$(form).submit(function(){
$('.alert-success').show();
event.preventDefault(); // if you want to send data only, do not reload page.
});
$(form) can be like if form has id or class: $('.myForm') , $('#myForm')

Categories