Angular Material input validation failed - javascript

Hello all i'm updating my forms to angular material style and i'd find something weird.
this form update the user data. so i'd load the data in a ng-model and put it in the form, so in that way the user can update its data.
the problem is the validation of one input that work in a strange way. First load with a wrong validation. all the data good, but that input doesn't validate.
<md-input-container class="md-block">
<!-- LABEL DNI-->
<label>D.N.I.</label>
<!-- INPUT DNI-->
<input type="text"
minlength="4"
md-maxlength="8"
maxlength="8"
placeholder="D.N.I."
ng-model="user.dni" name="dni" required/>
<!-- MENSAJES -->
<div ng-messages="changePerfil.dni.$error"
ng-if='changePerfil.dni.$dirty || changePerfil.dni.$touched'>
<div ng-message="required">Este campo no puede estar vacio.</div>
</div>
<!--ICONOS DE MENSAJE -->
<span ng-show="changePerfil.dni.$valid" class="glyphicon glyphicon-ok form-control-feedback"></span>
<span ng-show="changePerfil.dni.$dirty && changePerfil.dni.$invalid" class="glyphicon glyphicon-remove form-control-feedback"></span>
</md-input-container>
but if this is not weird. if i delete one character and type it again, it does, the validation is done.
there's someone with a clue of what's happening?
EDIT
i've found the problem but is rare... it's seems to not recognize as a string that property on my JSON
var user = {
nombre: "Paulo",
apellido: "Galdo Sandoval",
dni: "12345678",
domicilio: "Street 972",
email: "mail#hotmail.com",
estado: "Activo",
fechaCreacion: "2016-01-06",
fechaModificacion: "2016-06-16"
};
to make it work i must do this on my function:
$scope.user = datos.data;
var stringDni = datos.data.dni;
$scope.user.dni = stringDni.toString();

Related

JavaScript set a form fields initial value, to the same value of another field?

I am trying to handle some JavaScript work, which I don't have much experience with. I have a 2 part form where a user enters their personal info, and then company info. I am trying to set some of the company fields to what they already entered in their personal info.
I don't want the user to have to retype address, email, etc.
for example, I have...
<div class="form-group">
<label for="email">Email<span>*</span></label>
<input name="email" type="text" class="form-control required" id="email"placeholder="Email" value=".
{{email}}">
<span id="span_email" class="error-msg"></span>
And...
<div class="form-group">
<label for="comp_email">Company Email<span>*</span></label>
<input name="comp_email" type="text" class="form-control required" id="comp_email"placeholder="Email"
value="{{comp_email}}">
<span id="span_email" class="error-msg"></span>
How would I be able to set that second comp_email field to initially have the email info, so the user doesn't have to retype, unless they actually wanted to change the comp_email to another email address?
EDIT
It is all in one form, just separated by divs. Initially, when the page is loaded, the account section div is displayed, when the user hits next, it triggers the display of the business info.
<input type="button" onclick="nextFormPage(); window.scrollTo(0, 100)"
class="btn btn-danger btn-block" value="Next">
The nextFormPage() function just hides the first div and displays the second div.
You have tagged both javascript and jQuery so I'm not sure which you are using. But you can do this with a single line either way:
Javascript::
document.getElementById("comp_email").value = document.getElementById("email").value;
document.getElementById("email").value gets the value from the email input and we set the value of the document.getElementById("comp_email") by setting its value attribute:
jQuery:
$("#comp_email").val( $("#email").val() );
$("#email").val() get the value from the email input and $("#comp_email").val( ... ); sets the text passed in as the input value.
Javascript Working Example
function nextFormPage(){
document.getElementById("comp_email").value = document.getElementById("email").value;
}
<div class="form-group">
<label for="email">Email<span>*</span></label>
<input name="email" type="text" class="form-control required" id="email" placeholder="Email" value="">
<span id="span_email" class="error-msg"></span>
<div class="form-group">
<label for="comp_email">Company Email<span>*</span></label>
<input name="comp_email" type="text" class="form-control required" id="comp_email" placeholder="Email"
value="">
<span id="span_email" class="error-msg"></span>
<input type="button" onclick="nextFormPage(); window.scrollTo(0, 100)"
class="btn btn-danger btn-block" value="Next">
If your user is logged in, you should pass all of their information to the form, including their email. For example:
const logIn = () => {
... some code to get the user ...
... pass the user to the form, probably through an event listener...
let button = document.createElement("button")
button.textContent = "Edit"
button.addEventListener('click', () => {editYourStuff(user)}
}
const editYourStuff = user => {
... grab whatever your form is called ...
editForm.email.value = user.email
}
This should pre populate your form with the email

Cannot Modify The Value of HTML Elements From Node.js

I have an HTML form, which should be completed by the user. After completing the form, the introduced data is checked, in order to see whether the introduced username was introduced before or not. If the username is unique, then the input data is valid. If the username has already been used by someone else, I want to reload the sign up page, which is called signUp.html, but I also want to modify the values and placeholders of those fields contained by that HTML form. Excepting the Username and Password fields, I want every other field to contain the data, which was introduced by the user before. For sample, if the First Name field contained the value Toma, then I want, after reloading the page, the First Name field to have the value of Toma. On the other hand, I want to change the message of the placeholder of the Username field, which would be something like: Sorry, this username is invalid.... I tried to use the jsdom package, in order to acces the HTML file: signUp.html, which is to be found in public/views. The code of the HTML form is:
<form method="POST" action="signUp" style="margin-left: 5%; margin-right: 5%; margin-top: 5%" class="was-validated">
<div class="form-group">
<label style="color: #ffffff"> First Name </label>
<input type="text" name="firstName" class="form-control" placeholder="e.g.: Toma" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Second Name </label>
<input type="text" name="secondName" class="form-control" placeholder="e.g.: Alex" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Email </label>
<input type="email" name="email" class="form-control" placeholder="e.g.: somename#somedomain.com" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Username </label>
<input type="text" name="username" class="form-control" placeholder="e.g.: miauMiau23 (this is the name your friends will identify you with)" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Password </label>
<input type="password" name="password" class="form-control" placeholder="please, use a solid password, having a minimum of 6 characters, small and capital letters, as well as numbers and symbols!" required>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%"> Submit </button>
</form>
The code found in server.js, which tried to achieve what I've described before:
app.post('/signUp', urlencodedParser, function(req, res){
console.log("sorry... this username is invalid!");
res.render('signUp');
var { document } = (new JSDOM('public/views/signUp.html')).window;
var firstNameField = document.getElementsByName('firstName');
var secondNameField = document.getElementsByName('secondName');
var emailField = document.getElementsByName('email');
var usernameField = document.getElementsByName('username');
var passwordField = document.getElementsByName('password');
console.log(firstNameField.placeholder);
firstNameField.value = req.body.firstName;
secondNameField.value = req.body.secondName;
emailField.value = req.body.email;
usernameField.value = "";
usernameField.placeholder = "'" + req.body.username + "' is an invalid username...";
passwordField.value = "";
}
After reloading, the page loses all of the introduced data.
The reason is not working is because res.render will render the page on the server and then send it to the client. What you're doing after that is simply loading the HTML again into the server's memory with JSDOM and modifying it, at the end of the request that is just thrown away and doesn't effect what has already been sent to the client by res.render.
The correct way to do this would be to use a templating language (there are many to choose from) with your express.js server to dynamically render the page and inject the values you want in the right place. You can then simply pass the variables to the res.render to be available when rendering your template:
app.post('/signUp', urlencodedParser, function(req, res) {
console.log("sorry... this username is invalid!");
res.render('signUp', {
firstName: req.body.firstName,
secondName: req.body.secondName,
email: req.body.email,
error: "'" + req.body.username + "' is an invalid username...",
});
});
For example, if you went with Pug.js as a templating engine your sign-up page could look something like this (I've not included all formatting which should go into CSS):
form(method='POST' action='/signUp')
div.form-group
label(for='firstName') First Name
input#firstName.form-control(type='text', name='firstName', value=firstName, required)
div.form-group
label(for='secondName') Second Name
input#secondName.form-control(type='text', name='secondName', value=secondName, required)
div.form-group
label(for='email') Email:
input#email.form-control(type='email', name='email', value=email, required)
div.form-group
label(for='username') Username
if error:
input#username.form-control(type='text', name='username', placeholder=error)
else:
input#username.form-control(type='text', name='username', placeholder='e.g.: miauMiau23 (this is the name your friends will identify you with')
div.form-group
label(for='password') Password:
input#passwordw.form-control(type='password' name='password')
button.btn.btn-primary(type='submit') Submit

jQuery Validate plugin doesn't work in CodeIgniter

I'm trying to use the jQuery Validate plugin in a view of a CodeIgniter project using exactly like a lot of examples Internet, but doesn't work at all! I used a lot of sugerences that I found here in StackOverflow and other sites, but doesn't work. Here is my code:
<script src="<?php echo base_url(); ?>js/jquery-validation-1.16.0/dist/jquery.validate.js"></script>
<body>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-6">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Ingresar nueva empresa</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form id="formIngEmpresa">
<!-- RESPUESTA DE FORMULARIO -->
<!-- FIN RESPUESTA DE FORMULARIO -->
<div class="box-body">
<div class="form-group">
<label for="usuario_login">Nombre o Razón Social de la empresa</label>
<input type="input" class="form-control" id="nm_rs_empresa" placeholder="Ingrese login">
</div>
<div class="form-group">
<label for="usuario_password">Rut empresa</label>
<input type="input" class="form-control" id="nr_rut_empresa" placeholder="rut">
</div>
<div class="form-group">
<label for="usuario_password2">Descripcion empresa</label>
<input type="text" class="form-control" id="nm_desc_empresa" placeholder="Password">
</div>
<div class="form-group">
<label for="usuario_nm_usuario">Rubro de la empresa</label>
<input type="input" class="form-control" id="nm_rubro" placeholder="Ingrese nombres">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Ingresar</button>
<button type="reset" class="btn btn-default">Cancelar</button>
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.row -->
</section>
</body>
<script>
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
alert($("#formIngEmpresa").validate().form());
$("#formIngEmpresa").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
nm_rs_empresa: "required",
nr_rut_empres: "required",
nm_desc_empresa: "required",
nm_rubro: "required"
},
// Specify validation error messages
messages: {
nm_rs_empresa: "Porfavor introducir nombre empresa",
nr_rut_empres: "Por favor introducir rut",
nm_desc_empresa: "Por favor introducir una Descripcion",
nm_rubro: "Elija el rubro de la empreesa",
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
$("#submit").click(function(){
$("#formIngEmpresa").submit();
return false;
});
});
</script>
jQuery Validate plugin doesn't work in CodeIgniter
Right, it doesn't. jQuery is JavaScript and it only works in the browser, while CodeIgniter only works on the server. In other words, your framework does not matter to JavaScript as long as you send the proper HTML markup to the browser.
Here's why you're having difficulties...
You must have a name attribute on every input considered for validation and these names must exactly match the names you used when you declared your rules. Even your code comments say the same thing!
rules: {
// The key name on the left side is the name attribute <-- READ HERE!!
// of an input field. Validation rules are defined
// on the right side
nm_rs_empresa: "required", // <- 'nm_rs_empresa' must match the 'name' attribute
....
The click handler could be bypassing the plugin. Since jQuery Validate automatically captures the click event of the submit button and fully takes care of the submission, you absolutely would not need any additional event handlers. Remove this entire click handler... it's not needed.
$("#submit").click(function() { // REMOVE THIS
$("#formIngEmpresa").submit(); // REMOVE THIS
return false; // REMOVE THIS
}); // REMOVE THIS
Working DEMO: jsfiddle.net/wtdhvtc7/
First update the ID of the form
Instead if this
<form id="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js">
put
<form id="formIngEmpresa">
This is your first mistake, the ID of form must match with the JQuery methods $("#formIngEmpres").validate() where formIngEmpres is the ID of the form.

How to implement form validation with Angular JS and Bootstrap?

At a user registration web form I validate via ajax whether a username already exists in DB. When a username already exists, the corresponding input-text will go .has-error class.
Edit
I changed the ng-class attribute to {'has-error':signup.userUnavaliable()} but even though that the input is not seemly getting such class, in other words the mail input text is not getting red.
I place the directive at the wrapper as this is how the Bootstrap docs tell it.
This is how my form looks like now:
<form class="form-inline" role="form">
<div class="form-group" ng-class="{'has-error':signup.userUnavaliable()}">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Contraseña" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable">Registrar</button>
</form>
And this is my Controller:
app.controller('SignUpController',function ($scope, $http) {
$scope.userUnavaliable = function() {
return $scope.unavaliable
}
$scope.print = function(msg) {
console.log(msg)
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
$scope.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
$scope.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
Also, I'm trying to disable the button and it's not gettin such effect, so I think my controller has any issue.
As given in bootstrap validation states, if you want your label color to be changed according to the validation state of the input, you will have to apply ng-class on that.
Here is the sample code that I had written a little while. Please note that to take advantage of Angular JS validation states on form elements, you need to provide name to all input types.
This code would turn the input box plus label color red or green depending upon the validation state.
<div class="form-group"
ng-class="( newProfileForm.email.$dirty ? (newProfileForm.email.$valid ? 'has-success has-feedback' : 'has-error has-feedback' ) : ' ')"
>
<label class="col-sm-4 control-label">Email</label>
<div class="col-sm-6">
<input type="email" name="email" class="form-control" ng-model="user.mail" ng-required='true'>
<!-- Invalid Span -->
<span ng-if='newProfileForm.email.$invalid && newProfileForm.email.$dirty' class="glyphicon glyphicon-remove form-control-feedback"></span>
<!-- Valid Span -->
<span ng-if='newProfileForm.email.$valid' class="glyphicon glyphicon-ok form-control-feedback"></span>
<p ng-show="newProfileForm.email.$invalid && newProfileForm.email.$dirty" class="bg-danger pad">Please enter valid email.</p>
</div>
</div>
[EDIT] Explanation for name attribute.
Angular makes use of name attribute to determine the state of the input control. So, if you have a input control with name username. Even your form should have a name for angular validation states.
AngularJS would use the fallowing variables to check its validation state.
formname.username.$valid = if username is alright according to validation rules.
formname.username.$invalid = if username is invalid
formname.username.$dirty = if user has edited the input box
formname.username.$pristine = if user has not edited the input box.
Angular makes use of name attribute for validaiton.
And if you want your button to be disabled depending upon the availability of the user.
Use something like
<button class="btn btn-default" ng-disabled="unavaliable">Submit</button>
try
<div class="form-group" ng-class="{'has-error':signup.userUnavaliable()}">

How to implement Ember-Validations in Ember-App-Kit(EAK)

I have a ember-app-kit application. For the form I am using ember default views. But for form validations I have came across with this lib which everyone highly recommends. Ember Validations By Docyard . But I am not sure how to implement the same with my eak set-up.
Questions that I have:
1. Where should I add validations ?
2. What to declare when defining validations?
3. Errors how to show them on focus out or even on submit button ?
Say for example I have a sign up form and I want to validate firstname lastname, email, password, gender(select options) . How should I go about it ?
If possible please clarify the queries with a JSbin.
Validations should go to controller, unless your working with dyanmic formsets, which can be duplicated. Also u have to wrap ControllerObject into this
var AddController = Ember.ArrayController.extend(Ember.Validations.Mixin, {}
To start validation u have to make new Object named validations
You have to add input value to be validated
validations: {
newFirstname:{
format: { with: /^[A-Za-z-]{2,16}$/, allowBlank: true, message: 'Enter valid name.' }
},
newFamilyname: {
format: { with: /^[A-Za-z-]{3,16}$/ , message: 'Required field lastname.' }
}
},
Showing errors.
<div class="row">
<div class="col-md-6 col-xs-4">
<label>First name: </label>
{{input type="text" placeholder="First name" value=newFirstname class="form-control"}}
{{#if errors.newFirstname}}
<span class="error errorForValidation"><span class="glyphicon glyphicon-warning-sign"></span> {{errors.newFirstname}}</span>
{{/if}}
</div>
<div class="col-md-6 col-xs-4">
<label>*Last name: </label>
{{input type="text" placeholder="Family name" value=newFamilyname class="form-control"}}
{{#if errors.newFamilyname}}
<span class="error"><span class="glyphicon glyphicon-warning-sign"></span> {{errors.newFamilyname}}</span>
{{/if}}
</div>
</div><!--end row-->
Showing button when validation is flawless
<button type="submit" class="btn btn-primary" {{bind-attr disabled="isInvalid"}}{{action 'GetData'}}>Create</button>
JSBIN : http://emberjs.jsbin.com/iDeQABo/17/edit

Categories

Resources