I am using Mat control date range input control.
I want show error message when user misses to enter start date or end date.
here is my Html
<mat-form-field>
<mat-date-range-input [rangePicker]="pickerDate" disabled="this.form.controls[isCurrentDateChange].value==='False'">
<input formControlName="startDate" matStartDate matInput placeholder="Start date"/>
<input formControlName="endDate" matEndDate matInput placeholder="End date" />
</mat-date-range-input>
<mat-error *ngIf="this.form.controls['endDate'].value=='null'">
Please enter date.</mat-error>
<mat-datepicker-toggle matsuffix [for]="pickerDate"></mat-datepicker-toggle>
<mat-date-range-picker #pickerDate><mat-date-range-picker>
</mat-form-field>
Here is my ts file code
export class MyComponent implements OnInit{
form:FormGroup;
constructor()
{
this.form=new FormGroup({
startDate:new FormControl(null,[Validators.required]),
endDate:new FormControl(null,[Validators.required])
});
saveForm()
{
let editForm=this.form.value;
if(this.editForm.startDate==null)
{
this.editForm.controls['startDate'].markAsTouched();
return false;
}
else if(this.editForm.endDate==null)
{
this.editForm.controls['endDate'].markAsTouched();
return false;
}
else
{
return true;
}
}
}
I have tried diff ways to show error on the UI when Savebutton is clicked, but its not showing.
Please let me know if there is any way to show mat error on the UI.
I have tried ngIf as true but its not working for showing the error. Please suggest
From this line:
<mat-error *ngIf="this.form.controls['endDate'].value=='null'">
You are comparing whether the endDate's value is equal to 'null' which is a string. Thus the <mat-error> will not show when the endDate field is not inputted.
Solution 1
To check whether the endDate's value is null:
<mat-error *ngIf="!this.form.controls['endDate'].value">
Please enter date.
</mat-error>
Solution 2
Since you have applied Validators.required in your form control, you can check the validation error as below:
<mat-error *ngIf="this.form.controls['endDate'].errors?.required">
Please enter date.
</mat-error>
Demo # StackBlitz
Note: There are quite a lot of errors in your attached code, I suggest that you should test your code first before posting the question. It will help for debugging purposes.
Related
<mat-form-field>
<mat-label></mat-label>
<input [required] = "isMandatory? true:false" placeholder="Just a placeholder">
<mat-error *ngIf="isMandatory">mandatory field</mat-error>
</mat-form-field>
The above code is working fine and showing the error message when the textbox gets dirty or in focus. Now, I am trying to show before hand when the page loads initially.
<input [required] = "isMandatory? true:false" placeholder="Just a placeholder"
ng-model-options="{ updateOn: 'change blur' }">
Tried above approach with no luck. Is there any way to show error messages when form initially loads? Thanks!
One way to achieve this would be to add the following code inside ngOnInit():
ngOnInit(): void {
// FormControl or FormGroup initialization code
// ....................................
this.yourControl.markAsTouched();
// OR, if you want for the whole formGroup (and your're using at leat Angular 8)
this.yourFormGroup.markAllAsTouched();
}
This should do the trick and show the client side errors (required in your case) upfront.
I'm using Angular2 reactive forms, and I want to display a character count of a textarea as the user types.
I was hoping to just be able to include the form control's name.length in my html like so:
<div class="form-group">
<label for="incidentDescription">Brief Description of Incident</label>
<textarea id="incidentDescription" formControlName="incidentDescription" required [attr.maxLength]="maxIncidentDescriptionLength"></textarea>
<small><code>{{alaynaPage.incidentDescription.length}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
</div>
This "works" however the length of the form control lags one keystroke behind. So for example if I type a into the textarea {{alaynaPage.incidentDescription.length}} is 0. If i then type b (so string is ab) {{alaynaPage.incidentDescription.length}} is now 1.
How do I get this to work as expected?
I got it to work via a hack but there has to be an easier way:
//in component:
theLength: number = 0;
ngOnInit(): void {
this.buildForm();
(this.alaynaPageForm.controls['incidentDescription'] as FormControl).valueChanges.subscribe(value => {
// do something with value here
this.theLength = value.length;
});
}
//in my html:
<small class="form-text text-muted"><code>{{theLength}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
You just need to use a template reference variable
<textarea id="incidentDescription" formControlName="incidentDescription" #incidentDescription></textarea>
<small class="form-text text-muted"><code>{{incidentDescription.value.length}}</code> of <code>{{maxIncidentDescriptionLength}}</code> characters</small>
You want a hack, here's the hack. Use this:
{{alaynaPageForm.value?.incidentDescription?.length}}
In many forms I am developing with jQuery validation plugin I have many fields to fill like the following:
<p>
<label>Nome</label>
<span class="field">
<input type="text" name="nome" id="nome" class="smallinput"" value=""/>
</span>
</p>
and these fields are declared as required and if they are empty a message error is correctly shown. After that I would like the error message to hide when the user enters information. However, this does not happen. How can I set this? Moreover I have some fields which should contain email addresses whose rule is
email:{
required: true,
email: true,
},
and it happens that some email addresses are claimed to be not valid while instead they are. Is there a way to fix this?
SOLUTION
For those who might be interested, what I have tried is to add a class "req" to span elements which are required and when the user types in something and the value changes and is different from the void string, then an attribute style is added to generated label error, like that:
jQuery(".req").on('input',function(){
if (this.value != "")
jQuery(this).find("label").attr('style','display:none !important');
});
This seems to work fine. Obviously, if the value becomes again void then the red label error message is shown again.
I have this input code in my form:
<input maxlength="255" id="information_name" name="information[name]" oninvalid="check(this)" placeholder="Nombre Completo" required="required" size="30" style="width:528px;height:25px;" tabindex="3" type="text">
I change the oninvalid message with this javascritp code:
<script>
function check(input) {
if (input.value == "") {
input.setCustomValidity('Debe completar este campo.');
} else {
input.setCustomValidity('Debe corregir este campo.');
}
}
</script>
Here is the problem, if I clicked on submit and the field is empty, the field shome the error so I need to fill the field, but after fill the field, I still getting the warning even the fill is not empty.
What I'm doing wrong???
If you set a value with setCustomValidity() then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to take effects of your new input you have to clear the custom validity.
Simply you can use the following:
<input required maxlength="255" id="information_name" minlength=1 name="information[name]" oninvalid="setCustomValidity('Should not be left empty.')"
oninput="setCustomValidity('')" />
There is no need to use Javascript for this.
You can set a custom validity message with setCustomValidity, however any non-blank string will cause the field to act as if it had an invalid value. You need to setCustomValidity('') to clear the invalidated state of the field.
If your validity is simple and controlled via field attributes, you can use object.willValidate to do the test and set the custom validity message:
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')"
If you setCustomValidity to any value that is not the empty string then that will cause the input to be in the invalid state. So your condition is checking for a value, then setting the field to be invalid either way. Only setCustomValidity when the value in the field is actually invalid, otherwise set it to an empty string:
<script>
function check(input) {
if (input.value == "") {
input.setCustomValidity('Debe completar este campo.');
} else {
input.setCustomValidity('');
}
}
</script>
For me only oninvalid="this.setCustomValidity(this.willValidate ? '' :'You must choose the account type from the list')" works. There are lots of issues while using it with IE.
The issue is that the custom validity error message needs to be reset to blank/empty again, or the field will never validate (even with correct data).
I use oninvalid to set the custom validity error message, and then use onchange to set the message back to default (blank/empty), and then when the form is checked again it will correctly submit if data was corrected, or it will set the custom error message again if there is problem.
So something like this:
<input type="number" oninvalid="this.setCustomValidity('You need to enter an INTEGER in this field')" onchange="this.setCustomValidity('')" name="int-only" value="0" min="0" step="1">
for React Hooks Typescript users
const inputRef = useRef<HTMLInputElement>(null);
function setCustomValidity(customMsg?: string) {
inputRef.current?.setCustomValidity(
typeof customMsg === 'string' ? '' : t.errors.requiredField,
);
}
<input
ref={inputRef}
onInvalid={() => setCustomValidity()}
onInput={() => setCustomValidity('')}
/>
I am using the jQuery date picker calendar in a form. Once submitted the form passes params along via the url to a third party site. Everything works fine, except for one thing.
If the value inserted into the date field by the datepicker calendar is subsequently deleted, or if the default date, that is in the form on page load, is deleted and the form is submitted I get the following error:
"Conversion from string "" to type 'Date' is not valid."
The solution to my problem is really simple, I want to validate the text field where the date is submitted and send out a default date (current date) if the field is empty for any reason. The problem is I am terrible at Javascript and cannot figure out how to do this.
Here is the form code for my date field.
[var('default_date' = date)]
<input type="text" id="datepicker" name="txtdate" value="[$default_date]" onfocus="if (this.value == '[$default_date]') this.value = '';" onchange="form.BeginDate.value = this.value; form.EndDate.value = this.value;" />
<input type="hidden" name="BeginDate" value="[$default_date]"/>
<input type="hidden" name="EndDate" value="[$default_date]"/>
This is really old and probably solved, but what the heck.
Simplest way to do this is to add a little more javascript to the input's onchange event.
onchange="if( this.value.length > 0 ) { form.BeginDate.value = form.EndDate.value = this.value; } else { form.BeginDate.value = form.EndDate.value = '[$default_date]'; } " />
of course their are still all sorts of other problems associated with date validation, but this is a straightforward way to check for a blank value and return a default based on your current code structure.