Registration and validation form with angularjs - javascript

I have a problem with a registration form on angularjs, I want to controle the form before submit and how can i save user data in text file or json (any solution for saving data), I did not manage to do it.
For more information, I am working on a project : Interface for ReafctorErl public server - javascript (angular based).
registration.html :
<div class="register">
<div class="box">
<h4> Sign Up</h4>
<p> Enter your personal details below: </p>
</br>
<form role="frmRegister" name="frmRegister" ng-submit="register()" >
<div class="form-group">
<input class="form-control" type="text" id="fullname" placeholder="Full Name" ng-model="credentials.fullname"/>
</div>
<div class="form-group">
<input class="form-control" type="text" id="organisation :" placeholder="Organisation" ng-model="credentials.organisation" />
</div>
<div class="form-group">
<input class="form-control" type="text" id="address :" placeholder="Address" ng-model="credentials.address" />
</div>
<p> Enter your account details below: </p>
<div class="form-group">
<input class="form-control" type="email" id="email" placeholder="Email" ng-model="credentials.email" />
</div>
<div class="form-group">
<input class="form-control" type="text" id="username" placeholder="Username" ng-model="credentials.username" />
</div>
<div class="form-group" >
<input class="form-control" type="password" id="password" placeholder="Password" ng-model="credentials.password" />
</div>
<div class="form-group" >
<input class="form-control" type="password" id="password_again" placeholder="Password again" ng-model="credentials.password_again" />
</div>
<div class="form-actions">
Back
<button type="submit" class="btn btn-primary" onclick="return verif();">Submit</button>
</div>
</br>
</form>
</div>
</div>
<script language="javascript">
function verif(){
if (document.getElementById('password').value != document.getElementById('password_again').value) {
document.getElementById('password_again').setCustomValidity('Passwords must match.');
}
else {
document.getElementById('password_again').setCustomValidity('');
}
}
</script>
the controller file :
'use strict';
function RegisterCtrl($scope, reg) {
var credentials = {
fullname: "",
organisation: "",
address: "",
email: "",
username: "",
password: "",
password_again: ""
};
$scope.credentials = credentials;
$scope.restricted = window.restrictedMode;
$scope.register = function() {
if( $scope.frmRegister.fullname.length<1 ) {
alert("Full Name required!");
return false;
}
if( $scope.credentials.organisation.length<1 ) {
alert("Organisation required!");
return false;
}
if( $scope.credentials.address.length<1 ) {
alert("Address required!");
return false;
}
if( $scope.credentials.email.length<1 ) {
alert("Email required!");
return false;
}
if( $scope.credentials.username.length<1 ) {
alert("Username required!");
return false;
}
if( $scope.credentials.password.length<3 ) {
alert("Password required!");
return false;
}
if( $scope.credentials.password_again.length<3 ) {
alert("Password again required!");
return false;
}
reg.register($scope.credentials.fullname, $scope.credentials.organisation, $scope.credentials.address,
$scope.credentials.email, $scope.credentials.username, $scope.credentials.password, $scope.credentials.password_again, true);
};
}
Service file is :
'use strict';
/*just trying todo something here */
angular.module('referl.services').service('reg', function($q, $http, $location, $rootScope, $window) {
var reg = {
register: function(fullname, organisation, address, email, username, password, password_again, navigateOnSuccess) {
var parameters = {
fullname: fullname,
organisation: organisation,
address: address,
email: email,
username: username,
password: password,
password_again: password_again
};
$http.get("api/register", {params: parameters}).success(function(response) {
if(response.error) {
alert(response.error);
} else {
alert("Success");
}
});
}
};
$rootScope.reg = reg;
return reg;
});
Any help please ??
Thank you!

Better to follow https://docs.angularjs.org/guide/forms for html page that will reduce your angular controller code. and you can focus on service validation
Follow Binding to form and control state section of above link how to validate form.

To your input text's u can use: ng-pattern and attribute required
<form name="exampleForm" class="form-horizontal">
<div class="form-group">
<input class="form-control" type="text" id="fullname" placeholder="Full Name" ng-model="credentials.fullname" ng-pattern="INSERT PATTERN" required/>
</div>
</form>
to find patterns you can see here:
HTML5 pattern
and for valite the whole form
<button class="btn btn-primary" ng-click="myFunction()" ng-disabled="exampleForm.$invalid">Button</button>

Related

Validate email address having issue in vuejs?

<button type="submit"
class="register-button"
:class="(isDisabled) ? '' : 'selected'"
:disabled='isDisabled'
v-on:click=" isFirstScreen"
#click="persist" >
PROCEED
</button>
email:'',
maxemail:30,
validationStatus: function (validation) {
return typeof validation != "undefined" ? validation.$error : false;
},
computed: {
isDisabled: function(){
return (this.fullname <= this.max) || (this.mobile.length < this.maxmobile)
|| (this.gstin.length < this.maxgstin) ||
(this.email <= this.maxemail) || !this.terms || !(this.verified == true );
}
isEmail(e) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
{
this.msg['email'] = '';
} else{
this.msg['email'] = 'Invalid Email Address';
}
},
<input
type="email"
v-model.trim="$v.email.$model"
v-validate="'required'"
:class="{ 'is-invalid': validationStatus($v.email) }"
name="email"
class=" input-section"
placeholder="Enter your company email ID"
:maxlength="maxemail"
v-on:keypress="isEmail($event)"
id='email' v-model='email'
/>
<div v-if="!$v.email.required" class="invalid-feedback">
The email field is required.
</div>
<div v-if="!$v.email.maxLength" class="invalid-feedback-register">
30 characters only
{{ $v.user.password.$params.maxLength.min }}
</div>
Currently i am unable to validate the email address, even if i enter 2 or 3 characters button is enabling and moving to next page. I want to disable button until user enter valid email address.
Can some one help me on this, to solve the issue for the above code.
https://vuejsdevelopers.com/2018/08/27/vue-js-form-handling-vuelidate/
Try below steps it will help you to fix the issue.
Step 1: Install vuelidate using npm install --save vuelidate
Step 2: Register vuelidate in main.js
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
Step 3: Importrequired, email, minLength, sameAs from vuelidate/lib/validators
import { required, email, minLength, sameAs } from 'vuelidate/lib/validators'
Step 4: Add validations
validations: {
user: {
name: { required },
email: { required, email },
password: { required, minLength: minLength(6) },
confirmPassword: { required, sameAsPassword: sameAs('password') }
}
},
Step 4: Do the validation on button click
methods: {
submitRegistration () {
this.submitted = true
this.$v.$touch()
if (this.$v.$invalid) {
return false // stop here if form is invalid
} else {
alert('Form Valid')
}
}
}
Step 5: Design html template
<template>
<div>
<form #submit.prevent="submitRegistration" novalidate>
<div class="form-group">
<input type="text" class="form-control" placeholder="First Name" value="" v-model="user.name" />
<div v-if="this.submitted && !$v.user.name.required" class="invalid-feedback left">Enter Username</div>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter your company email ID" value="" v-model="user.email" autocomplete="off"/>
<div v-if="this.submitted && $v.user.email.$error" class="invalid-feedback left">
<span v-if="!$v.user.email.required">Email is required</span>
<span v-if="user.email && !$v.user.email.email">Enter valid email address</span>
<span v-if="user.email && $v.user.email.email && !$v.user.email.maxLength">Email is allowed only 30 characters</span>
</div>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Enter Password" value="" v-model="user.password" autocomplete="off" />
<div v-if="this.submitted && $v.user.password.$error" class="invalid-feedback left">
<span v-if="!$v.user.password.required">Password is required</span>
<span v-if="user.password && !$v.user.password.minLength">Password must be minimum 6 characters</span>
</div>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Confirm Password" value="" v-model="user.confirmPassword" autocomplete="off" />
<div v-if="this.submitted && $v.user.confirmPassword.$error" class="invalid-feedback left">
<span v-if="!$v.user.confirmPassword.required">Confirm Password is required</span>
<span v-if="user.confirmPassword && !$v.user.confirmPassword.sameAsPassword">Password and Confirm Password should match</span>
</div>
</div>
<input type="submit" class="btnRegister" value="Register" :disabled="this.isDisabled" />
</form>
</div>
</template>
Step 6: Button disabled till the form is valid
created () {
this.submitted = true
return this.$v.$touch()
},
computed: {
isDisabled () {
return this.$v.$invalid
}
},
You can refer for demo https://github.com/Jebasuthan/vue-vuex-vuelidate-i18n-registration-login-todo

JQuery regex email validation preventing form from submitting

I have a 'contact us' form on our website, people fill out name, email, and message and hit send. Currently the form won't submit if I have the email validation in my code.
Here is HTML form code:
<form role="form" id="feedbackForm">
<div class="form-group">
<label class="control-label" for="name">Full Name *</label>
<div class="input-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter your name.</span>
</div>
<div class="form-group">
<label class="control-label" for="email">Email Address *</label>
<div class="input-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email" required/>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<label class="control-label" for="reason">Contact Reason *</label>
<select name="reason" class="form-control" required>
<option value="General Inquiry">General Inquiry</option>
<option value="Schedule Appointment">Schedule Appointment</option>
<option value="Report Issue">Report Issue</option>
<option value="Provide Feedback">Provide Feedback</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="message">Message *</label>
<div class="input-group">
<textarea rows="5" class="form-control" id="message" name="message" placeholder="Enter Your Message" required></textarea>
<span class="input-group-addon"><i class="glyphicon glyphicon-unchecked form-control-feedback"></i></span>
</div>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="mykey"></div>
<span class="help-block" style="display: none;">Please check that you are not a robot.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-success btn-lg" data-loading-text="Sending..." style="display: block; margin-top: 10px;">Send Feedback
</button>
</div>
</form>
and here's the jquery code:
(function () {
//using regular expressions, validate email
var contactFormUtils = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
//if no form errors, remove or hide error messages
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
//upon form clear remove the checked class and replace with unchecked class. Also reset Google ReCaptcha
clearForm: function () {
$('#feedbackForm .glyphicon').removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
$('#feedbackForm input,textarea').val("");
grecaptcha.reset();
},
//when error, show error messages and track that error exists
addError: function ($input) {
var parentFormGroup = $input.parents('.form-group');
parentFormGroup.children('.help-block').show();
parentFormGroup.addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$(document).ready(function() {
$("#feedbackSubmit").click(function() {
var $btn = $(this);
$btn.button('loading');
contactFormUtils.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
//use bootstrap validator (https://github.com/1000hz/bootstrap-validator) if provided, otherwise a bit of custom validation
var $form = $("#feedbackForm"),
hasErrors = false;
if ($form.validator) {
hasErrors = $form.validator('validate').hasErrors;
} else {
$('#feedbackForm input,#feedbackForm textarea').not('.optional').each(function() {
var $this = $(this);
if (($this.is(':checkbox') && !$this.is(':checked')) || !$this.val()) {
hasErrors = true;
contactFormUtils.addError($(this));
}
});
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
}
//if there are any errors return without sending e-mail
if (hasErrors) {
$btn.button('reset');
return false;
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "php/sendmail.php",
data: $form.serialize(),
success: function(data) {
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
},
complete: function() {
$btn.button('reset');
}
});
return false;
});
$('#feedbackForm input, #feedbackForm textarea').change(function () {
var checkBox = $(this).siblings('span.input-group-addon').children('.glyphicon');
if ($(this).val()) {
checkBox.removeClass('glyphicon-unchecked').addClass('glyphicon-check').css({color: 'green'});
} else {
checkBox.removeClass('glyphicon-check').addClass('glyphicon-unchecked').css({color: ''});
}
});
});
})();
When I remove this bit of code that validates if the email is in correct format then the form sends to my email right away.
var $email = $('#email');
if (!contactFormUtils.isValidEmail($email.val())) {
hasErrors = true;
contactFormUtils.addError($email);
}
Which in turn leads to this bit, I believe :
if (hasErrors) {
$btn.button('reset');
return false;
}
if I comment out 'return false;' then it sends the form
I can't find what part of the email validation prevents the form from submitting?
Maybe you have another element with id="email" somewhere.
Maybe try:
$('#feedbackForm input[type=email]').each(function() {
if (!contactFormUtils.isValidEmail(this.val())) {
hasErrors = true;
contactFormUtils.addError(this);
console.log("ERROR: Invalid email: "+this.val()+" in input "+this.attr("name"));
}
})

validate popup, then open another popup

I am using bootstrap to create a popup signup form. Once the user clicks submit and it has been validated I want to close that popup and open another saying thank you. I have tried using .modal('show') in popupvalidation.js but that did not seem to work. All it did was open both at the same time.
Here is the code:
index.php
<form name="popup" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return popupValidation();" method="post">
<div class="row">
<input name="firstName" type="text" class="form-control" id="inputFirstName" placeholder="First Name">
<input name="lastName" type="text" class="form-control" id="inputLastName" placeholder="Last Name">
</div>
<div class="row">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="youremail#email.com">
</div>
<div class="row">
<input name="password" type="password" class="form-control" id="inputPassword" placeholder="password">
</div>
<div class="row">
<input name="repeatPass" type="password" class="form-control" id="retypePassword" placeholder="Retype password">
</div>
<div class="row">
<input name="trainer" type="checkbox"/> Sign up as trainer
</div>
<div class="modal-footer popup-footer">
<p id="error">Please make sure all fields are filled out</p>
<input type="submit" class="btn btn-default submit" value="Register">
</div>
</form>
popupvalidation.js
function popupValidation() {
var fname = document.forms["popup"]["firstName"].value;
var lname = document.forms["popup"]["lastName"].value;
var pass = document.forms["popup"]["password"].value;
var repass = document.forms["popup"]["repeatPass"].value;
var email = document.forms["popup"]["email"].value;
if (fname==null || fname=="") {
document.getElementById("inputFirstName").focus();
document.getElementById("error").innerHTML= 'Please enter your First Name';
document.getElementById("error").style.display = 'block';
return false;
}
if (lname==null || lname=="") {
document.getElementById("inputLastName").focus();
document.getElementById("error").innerHTML= 'Please enter your Last Name';
document.getElementById("error").style.display = 'block';
return false;
}
if (email==null || email=="") {
document.getElementById("inputEmail").focus();
document.getElementById("error").innerHTML= 'Please enter a valid email';
document.getElementById("error").style.display = 'block';
return false;
}
if (pass==null || pass=="") {
document.getElementById("inputPassword").focus();
document.getElementById("error").innerHTML= 'Please enter a password';
document.getElementById("error").style.display = 'block';
return false;
}
if (repass==null || repass=="") {
document.getElementById("retypePassword").focus();
document.getElementById("error").innerHTML= 'Please retype password';
document.getElementById("error").style.display = 'block';
return false;
}
if (repass!=pass) {
document.getElementById("retypePassword").focus();
document.getElementById("error").innerHTML= 'Passwords do not match';
document.getElementById("error").style.display = 'block';
return false;
}
}

basic form validation not working

This simple form validation is not working and it's irritating me. Please let me know what is the problem. I have been trying to find a bug for almost two hours but can't find it. Please help me.
Take a look at code:
function validate()
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
return false;
}
return( true );
}
<div class="form">
<h2> Contact Us </h2>
<form name="c_form" action="#" method="post" onsubmit="return(validate());">
<div class="input">
<input type="text" name="full_name" id="full_name" placeholder="Full Name">
</div>
<div class="input">
<input type="text" name="email" id="email" placeholder="Email Address">
</div>
<div class="input textarea">
<textarea id="message" name="message" placeholder="Enter Message Here"></textarea>
</div>
<div class="input button">
<button id="button"> Send </button>
</div>
</form>
</div>
Why not using HTML5's native "required" attribute? Nowadays, most browsers will happily interpret it without problems. If you want to support older browsers, just use a library like h5validate, but (please) keep your html clean.
Take a look on the same form using those attributes. No JS, no DIV containers, just plain native Html:
input, textarea {
display:block;
margin-bottom: 5px;
}
<h2> Contact us without JS </h2>
<form name="c_form" action="#" method="post">
<input type="text" name="full_name" placeholder="Full Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<textarea name="message" placeholder="Enter Message Here" required></textarea>
<button type="submit"> Send </button>
</form>
I made a few changes and it works. The following snippet:
Include jQuery.
Add all the contents inside $(function () {}).
function validate ()
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
return false;
}
return( true );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form">
<h2> Contact Us </h2>
<form name="c_form" action="#" method="post" onsubmit="return(validate());">
<div class="input">
<input type="text" name="full_name" id="full_name" placeholder="Full Name">
</div>
<div class="input">
<input type="text" name="email" id="email" placeholder="Email Address">
</div>
<div class="input textarea">
<textarea id="message" name="message" placeholder="Enter Message Here"></textarea>
</div>
<div class="input button">
<button id="button"> Send </button>
</div>
</form>
</div>
I added an id of "c_form" to your html and removed the onsubmit property and used the following javascript code, which seemed to work. The key is calling ev.preventDefault();
$(document).ready(function () {
$("#c_form").submit(validate);
});
function validate(ev)
{
if( $("#full_name").val() == "" )
{
alert( "Please provide your name!" );
$("#full_name").focus() ;
ev.preventDefault();
return false;
}
if( $("#email").val() == "")
{
alert( "Please provide your Email!" );
$("#email").focus() ;
ev.preventDefault();
return false;
}
if( $("#message").val() == "" )
{
alert( "Please Enter Message" );
ev.preventDefault();
return false;
}
return true;
}

How to check if function returns true

I have a web form that submits if my function validate form returns true in that function i wrote an if statement that if another function called usernamecheck returns true then return the validateform function true. I dont want the form to submit unless you click the button to check the username. I know i didnt write this the best way i hope you understand
<!-- Signup Form -->
<form name='signup' action="subscription.php" onsubmit="return validateForm();" method="post" >
<input type="text" id="signupUsername" name="signupusername" placeholder="Business Name" tabindex=1 required>
<input type="password" id="signupPassword" placeholder="Password" name="signuppassword" tabindex=2 required> <br>
<input type="text" id="ownerName" placeholder="Owner's Name" name="ownername" tabindex=3 required>
<input type="email" id="signupEmail" placeholder="Email" name="signupemail" tabindex=4 required>
<input type="tel" id="signupphoneNumber" placeholder="Phone Number" name="signupphonenumber" tabindex=5 required>
<input type="image" id="signupSubmit" src="images/signupBtn.jpg">
<input type="text" id="city" placeholder="City" name="city" tabindex=6>
<input type="text" id="state" placeholder="State" name="state" tabindex=7>
This is the button that you click to check your username if it exists
<input type="button" id='check' value="Check It">
//
</form>
<script type="text/javascript">
Below there is the function where if you click the button above it checks the function usernamecheck
$(function() {
$( "#check" ).click(function() {
return usernamecheck();
});
});
Below is the validateForm function where if usernamecheck returns true it returns true as well and submits the form
function validateForm()
{
if(usernamecheck() && $("#signupUsername").val().length < 4) {
return true;
}
}
function usernamecheck() {
$.post( "checkusername.php", { username: $("#signupUsername").val() })
.done(function( data ) {
result = JSON.parse(data);
if(result["status"]== "Username is taken")
{
alert("username is taken");
return false;
}
else if(result["status"]== "Username is Available") {
alert("username is Available");
return true;
}
else {
alert('You did not check the username');
}
});
}
</script>
<!-- Map Logo -->
<img src='images/map.jpg' id="map" class='menuitems'>
<!-- About Us Logo -->
<img src='images/aboutus.jpg' id="aboutus" class='menuitems'>
<!-- People Logo -->
<img src='images/people.jpg' id="people" class='menuitems'>
</div>
</div>
</div>
</body>
</html>

Categories

Resources