I have 2 fields that get validated.
The issue is these fields are getting set with values by Chrome, such as the saved password and email.
So when the page loads the 2 fields (email + password) which have the right values as set via Chrome but the 2nd field is shown as invalid.
I am trying to detect changes after the page has loaded.
I have tried calling the changeDetectorRef from ngInit but it did not work.
When I click on the page the field then shows that it is valid.
Within the constructor:
this.form = fb.group({
'email': ['', Validators.compose([
Validators.required,
Validators.minLength(4),
EmailValidator.validate])],
'password': ['', Validators.compose([
Validators.required,
Validators.minLength(6)])]
});
this.email = this.form.controls['email'];
this.password = this.form.controls['password'];
I have tried:
ngOnInit() {
this.zone.run(() => {
this.email.updateValueAndValidity();
this.password.updateValueAndValidity();
});
}
But still no good.
I find it odd that the first field is shown as valid but the 2nd one is not.
It is a password field so that might have something to do with it?
Both fields are of type AbstractControl.
Here is the html:
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="form-horizontal">
<div class="form-group row" [ngClass]="{'has-error': (!email.valid), 'has-success': (email.valid)}">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input [formControl]="email" type="email" class="form-control" id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group row" [ngClass]="{'has-error': (!password.valid), 'has-success': (password.valid)}">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input [formControl]="password" type="password" class="form-control" id="inputPassword3" placeholder="Password">
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10">
<button [disabled]="!form.valid" type="submit" class="btn btn-default btn-auth">Sign in</button>
</div>
</div>
</form>
Related
I want to use the same form to perform two different operations, and hide and display part of the form on a condition. Let's say if the text of the submit button is "SAVE" admissionNumber input field will not display but if the button text of the submit button is "UPDATE" admissionNumber input field will display. Below is the code sample
registerForm.html the same for being used to register and update student information
<div layout:fragment="content" class="container mySpace">
<form method="post" th:object="${student}" th:action="#{/register}">
<div class="card cardspace">
<h5 class="card-header" th:text="${chead}"></h5>
<div class="card card-body">
<div class="form-row">
<div class="col-9">
<div class="row">
i want to be able hide admissionNumber field if the btname is save and display it if the btname changes to update
<div class="form-group col" th:if="${btnname} == 'Submit'">
<label for="admissionNumber">Admission Number</label> <input
type="text" class="form-control" id="admissionNumber"
th:field="*{admissionNumber}">
<div class="text text-danger"
th:if="${#fields.hasErrors('admissionNumber')}"
th:errors="*{admissionNumber}"></div>
</div>
<div class="form-group col" th:unless="${btnname} == 'Update'">
<label for="admissionNumber">Admission Number</label> <input
type="text" class="form-control" id="admissionNumber"
th:field="*{admissionNumber}">
<div class="text text-danger"
th:if="${#fields.hasErrors('admissionNumber')}"
th:errors="*{admissionNumber}"></div>
</div>
<div class="form-group col">
<label for="firstName">First Name</label> <input type="text"
class="form-control" id="firstName" th:field="*{firstName}">
<div class="text text-danger"
th:if="${#fields.hasErrors('firstName')}"
th:errors="*{firstName}"></div>
</div>
<div class="form-group col">
<label for="lastName">Last Name</label> <input type="text"
class="form-control" id="lastName" th:field="*{lastName}">
<div class="text text-danger"
th:if="${#fields.hasErrors('lastName')}"
th:errors="*{lastName}"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" th:text="${btnname}"></button>
</form>
student controller class
#Controller
public class StudentController {
#Autowired
private StudentServices studentServices;
displays the registration form
#GetMapping("/register")
public String showStudentRegistrationForm(Model model ) {
model.addAttribute("student", new Student());
model.addAttribute("chead", "Student Enrollment");// for card-header title h5 tag
model.addAttribute("btnname", "Submit"); // for button text
return "views/studentRegistrationForm";
}
displays the edit or update form
#GetMapping("/editStudent")
public String showStudentRegistrationEditForm(Model model ) {
model.addAttribute("student", new Student());
model.addAttribute("chead", "Edit Student Enrollment");
model.addAttribute("btnname", "Update");
return "views/studentRegistrationForm";
}
}
what you want is th:if tag, you got it almost right but whole wxpression needs to be in brackets th:if="${btnname == 'Submit'}"
I followed same sample with the code and tried to show validation when user removes the text in the input and show display messages.Unfortunately, when I remove the text field it does not show anything. Could you please check the code and tell me why I can not show the validation message ?
Regards
Alper
<label for="name">SA / Rentennummer 005 :</label>
<input type="text" class="form-control" id="name" required
[(ngModel)]="Input.name" name="name" #name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
name is required
</div>
In The typescript :
Input= { name:'Alper'};
form : FormGroup;
this.form = fb.group({
name : new FormControl({value: null}, Validators.compose([Validators.required, Validators.maxLength(100)]))
});
<form class="form-details" role="form" name="registrationForm" [formGroup]="userForm">
<div>
<div class="row input-label">
<label class="form-label" for="name">First name</label>
<input
[formControl]="form.controls['name']"
type="text"
class="form-control"
id="form"
name="form">
</div>
<div *ngIf="!form.controls['name'].valid">field is required</div>
</div>
</form>
This question already has an answer here:
Using jquery.validation equalTo( other ) to ensure "Sunday" is the inputted value
(1 answer)
Closed 8 years ago.
I have the following code
$("#emailForm").validate({
rules: {
"UserPasswordReset.EmailAddress": {
maxlength: 256,
email: true,
},
"UserPasswordReset.ConfirmEmailAddress": {
maxlength: 256,
email: true,
equalTo: "#UserPasswordReset.EmailAddress"
}
}
});
When I fill in the below form and press submit I says on the confirm box please enter the same value so I check, double check and for the love of god I check again, but still I get please enter the same value even though both fields are identical.
<div id="home" class="tab-pane active" role="tabpanel">
<div class="form-group">
<label class="col-sm-1 control-label no-padding-right" for="form-field-1-1"> Email</label>
<div class="col-sm-9">
<input id="emailaddress" class="col-xs-10 col-sm-5" type="text" value="" name="UserPasswordReset.EmailAddress" data-val-required="The EmailAddress field is required." data-val="true" autocomplete="off" placeholder="Please enter your email address">
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label no-padding-right" for="form-field-1-1"> Confirm </label>
<div class="col-sm-9">
<input id="confirm_email" class="col-xs-10 col-sm-5" type="text" value="" name="UserPasswordReset.ConfirmEmailAddress" autocomplete="off" placeholder="Please confirm your email address">
</div>
</div>
<button id="btnSaveEmail" class="btn btn-info pull-right" type="Submit" value="true" name="SaveEmailAddress"> Update Email </button>
</div>
What am I doing wrong here?
You ConfirmEmailAddress rule has
equalTo: "#UserPasswordReset.EmailAddress"
You don't have a control with id="UserPasswordReset.EmailAddress" (only one with id="emailaddress"). Change it to
equalTo: "#emailaddress"
I am using jQuery and form validator plugin and it works fine except one page shown below.
HTML:
<form method="POST" enctype="multipart/form-data" id="frmReg" class="form-horizontal" novalidate="novalidate">
<input type="hidden" name="mode" id="mode" value="insert">
<input type="hidden" name="fileName" id="fileName">
<div class="control-group">
<label id="fileLabel" class="control-label">*File Name</label>
<div class="controls">
<input type="file" name="file" id="file" placeholder="Select file" required="required" class="valid">
</div>
</div>
<div class="control-group">
<label class="control-label">*Package Name</label>
<div class="controls">
<input type="text" name="id.appId" id="appId" placeholder="Type group ID" tabindex="0" class="valid">
</div>
</div>
<div class="control-group">
<label class="control-label">*Application Title</label>
<div class="controls">
<input type="text" name="appName" id="appName" placeholder="Type application name" class="valid">
</div>
</div>
<div class="control-group">
<label class="control-label">*Version</label>
<div class="controls">
**<input type="text" name="id.version" id="version" placeholder="Type version" tabindex="0" class="valid">**
</div>
</div>
<div class="control-group">
<label class="control-label">Description</label>
<div class="controls">
<textarea name="description" id="description" placeholder="Type description" class="valid"></textarea>
</div>
</div>
<div class="modal-footer">
<button aria-hidden="true" data-dismiss="modal" class="btn">Close</button>
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
JS:
$("#frmReg").validate({
ignore: "", //for hidden field
rules: {
version: {
required: true,
number: true
}
},
messages: {
version: {
required: "Enter version number",
number: "Decimal numbers only allowed."
}
}
});
**$("#frmReg").validate().element("#version");**
It works when I use 'version' as the input name but I have to use 'id.version' as input name rather than 'version' because of server-side framework. But when I use the name, the validation code always returns true, even when I type any special characters and alphabets.
How can I still use id.version for the element?
Your answer would be appreciated.
As per the documentation...
Fields with complex names (brackets, dots)
If your form consists of fields using names that aren't legal JavaScript identifiers, you have to quote those names when using the rules option
Simply put quotes around the name containing dots...
$("#frmReg").validate({
ignore: "", //for hidden field
rules: {
'id.version': {
required: true,
number: true
}
},
messages: {
'id.version': {
required: "Enter version number",
number: "Decimal numbers only allowed."
}
}
});
Working DEMO: http://jsfiddle.net/A2ZdL/
Been struggling with this for about 4 hours, I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to create a Company. This is built in CodeIgniter.
I'm having issues with input type="submit" and input type="button".
I only have 1 required field, which is Company Name. If I use input type="button", the validation will fire correctly inside of the modal, however the form will only INSERT just the company name, along with company_id, user_id, active, and cdate.
Now if I use input type="submit", all the data inserts fine. However, the validation breaks and I get a "Page cannot be found" after clicking "Create Company", the data is still inserting though.
Any ideas? Thanks! New to AJAX...
My AJAX function:
$(document).ready(function(){
$('#create_btn').live('click', function(){
//we'll want to move to page specific files later
var name = $('#name').val();
$.ajax({
url: CI_ROOT + "members/proposals/add_client",
type: 'post',
data: {'name': name },
complete: function(r){
var response_obj = jQuery.parseJSON(r.responseText);
if (response_obj.status == 'SUCCESS')
{
window.location = CI_ROOT + response_obj.data.redirect;
}
else
{
$('#error_message2').html(response_obj.data.err_msg);
}
},
});
});
});
My controller function which handles the insert:
function add_client()
{
$this->form_validation->set_rules('name', 'Company Name', 'trim|required|xss_clean');
load_model('client_model', 'clients');
load_model('industry_model');
$user_id = get_user_id();
$company_id = get_company_id();
if (!$user_id || !$company_id) redirect('home');
if ($_POST)
{
if ($this->form_validation->run() == TRUE)
{
$fields = $this->input->post(null , TRUE);
$fields['user_id'] = $user_id;
$fields['company_id'] = $company_id;
$fields['active'] = 1;
$fields['cdate'] = time();
$insert = $this->clients->insert($fields);
if ($insert)
{
$this->message->set('alert alert-success', '<h4>Company has been added</h4>');
header('location:'.$_SERVER['HTTP_REFERER']);
}
else
{
$this->message->set('alert alert-error', '<h4>There was an issue adding this Company, please try again</h4>');
}
}
else
{
$err_msg = validation_errors('<div class="alert alert-error">', '</div>');
$retval = array('err_msg'=>$err_msg);
$this->ajax_output($retval, false);
}
}
$this->data['industries'] = array(0=>'Select Industry...') + $this->industry_model->dropdown('industry');
$this->insertMethodJS();
$this->template->write_view('content',$this->base_path.'/'.build_view_path(__METHOD__), $this->data);
$this->template->render();
}
And finally, my view:
<div class="modal hide fade" id="milestone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="width: 600px !important;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Add a Company</h3>
</div>
<div class="modal-body">
<?php echo form_open_multipart(base_url().'members/proposals/add_client', array('class' => '', 'id' => 'client_form'));?>
<div id="error_message2"></div>
<div class="row-fluid">
<div class="span5">
<input type="hidden" name="cdate" id="cdate" value="" />
<div class="control-group">
<label class="control-label">Company Name: <span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="name" name="name" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company Abbreviation:<span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="abbreviation" name="abbreviation" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company Image: </label>
<div class="controls">
<input type="file" name="client_image" size="20" />
</div>
</div>
</div>
<div class="span5">
<div class="control-group">
<label class="control-label">Website:</label>
<div class="controls">
<input type="text" id="website" name="website" value=""/>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span5" style="margin-top: 25px;">
<div class="control-group">
<div class="controls">
<p><strong>Client</strong></p>
</div>
</div>
<div class="control-group">
<label class="control-label">Address 1:</label>
<div class="controls">
<input type="text" id="address1" name="address1" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Address 2:</label>
<div class="controls">
<input type="text" id="address2" name="address2" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">City:</label>
<div class="controls">
<input type="text" name="city" id="city" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">State:</label>
<div class="controls">
<?= form_dropdown('state', usa_state_list(), set_value('state'), 'id=state'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Zip:</label>
<div class="controls">
<input type="text" id="zip" name="zip" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Country:</label>
<div class="controls">
<?= form_dropdown('country', country_list(), set_value('country'), 'id=country'); ?>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button type="submit" class="btn btn-primary" id="create_btn">Create Company</button>
</div>
</form>
</div>
So again, to summarize. With input type="button", my validation works great within the modal and only the Company Name is inserting into the database along with company_id, user_id, active, and cdate.
Now, with input type="submit", all data inserts great, however validation fails and I get a redirect to a page cannot be found.
Again, thanks!
The issue is with your ajax function call.
You need to prevent the form from firing (and thus submitting via post to the url in action):
Change:
$('#create_btn').live('click', function(){
To:
$('#create_btn').live('click', function(e){
e.preventDefault();
This should fix the issue. If it doesn't, let me know and I'll do more digging. I would also recommend switching live to on so that you future-proof yourself. on handles the same stuff as live, bind, etc. in a single function with more efficiency.
Edit: To explain what's going on (and why you must use e.preventDefault();), it is because <input type="submit"> will actually submit the form to the url specified in the <form> tag's action attribute. Thus, what's happening with your code is that your javascript is running as soon as you click the button, and then the native browser submit event is occurring immediately afterwards.