Angular 5 - Reactive forms doesn't validate form on submit - angular-reactive-forms

I have a simple form as below:
some.component.html
<form class="example-form" novalidate (ngSubmit)="onSubmit()" autocomplete="off" [formGroup]="testform">
<input type="text" formControlName="name" class="form-control" placeholder="Enter name" required/>
<app-show-errors [control]="claimform.controls.name"></app-show-errors>
<button type="submit" (click)="onSubmit()">Next</button>
</form>
some.component.ts
ngOnInit() {
this.testform= new FormGroup({
name: new FormControl('', { validators: Validators.required})
}, {updateOn: 'submit'});
}
onSubmit() {
if (this.testform.valid) {
alert('saving data');
} else {
this._validationService.validateAllFormFields(this.testform);
}
}
validationService.ts
validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
Reference
Problem
The form will validate on submit if left blank, but even after filling the value when I check this.testform.valid it returns false. But if I remove updateOn:'submit' on form then it validates on blur of input control and when value is entered it validates form return true. Not sure if updateOn is working fine or not or whether I've implemented this in a proper way. Could someone point me in the right direction.

in your HTML you have two calls to onSubmit() function, from submit button:
<button type="submit" (click)="onSubmit()">Next</button>
and from the form:
<form class="example-form"
ovalidate
(ngSubmit)="onSubmit()"
autocomplete="off"
[formGroup]="testform">
The first call to be triggered is the button's trigger, which actually does nothing in terms of updating your reactive form, since you set FormGroup's option to {updateOn: 'submit'}. The second call to be triggered is the form's trigger, which does actual form update.
Here is FormGroup directive config:
#Directive({
selector: '[formGroup]',
providers: [formDirectiveProvider],
host: {'(submit)': 'onSubmit($event)', '(reset)': 'onReset()'},
exportAs: 'ngForm'
})
as we can see in host property DOM form's submit (triggered by hitting ENTER while focused within form or clicking form's submit button) will call onSubmit() function:
onSubmit($event: Event): boolean {
(this as{submitted: boolean}).submitted = true;
syncPendingControls(this.form, this.directives);
this.ngSubmit.emit($event);
return false;
}
which then will call syncPendingControls() function:
export function syncPendingControls(form: FormGroup, directives: NgControl[]): void {
form._syncPendingControls();
directives.forEach(dir => {
const control = dir.control as FormControl;
if (control.updateOn === 'submit' && control._pendingChange) {
dir.viewToModelUpdate(control._pendingValue);
control._pendingChange = false;
}
});
}
which updates a model at last.
So, in your case, just remove (click)="onSubmit()" from the submit button:
<button type="submit">Next</button>
also you do not need required DOM element property on your input, since you set it using Reactive Forms API validators: Validators.required and since you set your form to novalidate which cancels HTML5 form validation.

Related

React Redux Form failing required validation even when set with initialValues

I have a React Redux Form which has a few required fields and has its initial values set with initialValues prop
The values initialize fine, but when I try to save the form it errors saying the field is required (even though there's a value in there). If I simply CLICK into the field then save again everything works fine!
I have tried every way I can find using initialize/reset/destroy/change/blur/etc to manually touch or set the field all to no avail
reduxForm({
form: 'formName',
touchOnChange: true,
touchOnBlur: true
}),
useEffect(() => {
if (initialValues && initialValues.field) {
change(field, value)
blur(field, value)
}
}, [initialValues])
and a whole slew of different options as above
Same behavior if I try to reset and re-init the form, or call change. If I just click into the field though then the validation passes as expected.
Also tried enableReinitialize: true but that didn't change the behavior either
initialValues is set via an async call which updates redux state var, I'm guessing this is the issue at hand. I've been unable to reproduce with any of the mvp sandbox examples.
The values are getting set just fine in the fields but it's like the validators just aren't checking the field after the initialValue is set unless the user performs a mouse click in them.
How can I tell the form there's already a value in there just check, without the user manually clicking into the field
-- some new info
If I manually touch and then blur the field ... the validation fails immediately instead of waiting for submit to be pressed, so it really must think there's no value in the input until there's a mouse click there
It looks like you are in need of a form validation. The below is a example form / form validation from https://redux-form.com/6.0.1/examples/submitvalidation/.
submit.js
import { SubmissionError } from 'redux-form'
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
function submit(values) {
return sleep(1000) // simulate server latency
.then(() => {
if (![ 'john', 'paul', 'george', 'ringo' ].includes(values.username)) {
throw new SubmissionError({ username: 'User does not exist', _error: 'Login failed!' })
} else if (values.password !== 'redux-form') {
throw new SubmissionError({ password: 'Wrong password', _error: 'Login failed!' })
} else {
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`)
}
})
}
export default submit
SubmitValidationForm.js
import React from 'react'
import { Field, reduxForm } from 'redux-form'
import submit from './submit'
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type}/>
{touched && error && <span>{error}</span>}
</div>
</div>
)
const SubmitValidationForm = (props) => {
const { error, handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit(submit)}>
<Field name="username" type="text" component={renderField} label="Username"/>
<Field name="password" type="password" component={renderField} label="Password"/>
{error && <strong>{error}</strong>}
<div>
<button type="submit" disabled={submitting}>Log In</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
export default reduxForm({
form: 'submitValidation' // a unique identifier for this form
})(SubmitValidationForm)
Good luck!

Reading form inputs?

How would you read the input value ?
On the reacjs site I see very complicated way !!
https://reactjs.org/docs/forms.html
I just want to read the value and submit it via ajax fetch() request. I.e. I don't need to manage bindings, events and such ...
The easiest way by far to read values from html controls is by using an event handler.
export default class myComponent extends Component {
person = {};
onChange = field => e => {
this.person[field] = e.target.value;
};
render() {
return (
<Input
id="firstName"
name="firstName"
autoComplete="firstName"
autoFocus
onChange={this.onChange('FirstName')}
/>
);
}
}
In the above code snippet we are basically telling react to fire the onChange member on an update of firstName control update. Our method will receive an event e, that has a handle to our control and we can basically probe it's value member to get what's typed in (much like jquery's $('#element').value()).
Why is it the easiest method? because it's generic enough to allow you to handle multiple inputs in a react component. Notice that, I'm also instructing React to pass me the control name in addition to the event, and using this method I can basically know exactly which of my inputs (in case of multiple) caused the event to fire.
Reading user input value is feasible and recommended via event handlers.
Below example would explain how to read input value and send it to the backend via fetch when Form is submitted
class Test extends Component{
constructor(props){
super(props);
this.state = {
name: “”
}
}
handleChange = event => {
this.setState({name: event.target.value});
}
handleSubmit = () => {
//send the value via fetch backend I.e., this.state.name
}
render(){
const { name } = this.state;
render(
<form onSubmit={this.handleSubmit}
<label>
Name:
<input type="text" value={name} onChange={this.handleChange} name="name" />
</label>
<input type="submit" value="Submit" />
</form>
)
}
}

Angular 5 ngSubmit #Output fires twice

CUSTOM COMPONENT
// ...
#Output() submit: EventEmitter < any > = new EventEmitter();
// ...
onFilterSubmit($event): void {
this.submit.emit($event);
this.formData = {
minDate: new Date().toISOString(),
maxDate: new Date().toISOString()
};
}
<form (ngSubmit)="onFilterSubmit(formData)">
<!-- -- -->
<button mat-button
mat-raised-button
[disabled]="reqsForm.form.invalid"
type="submit"
color="primary">
{{labels.submit}}
</button>
</form>
OUTER COMPONENT
// ...
onFilterSubmit($event): void {
console.info("FORM SUBMIT", $event);
}
<custom-component (submit)="onFilterSubmit($event)">
<!-- -- -->
</custom-component>
OUTPUT
FORM SUBMIT > Object
FORM SUBMIT > Object
The reason why this was happening is that an event called "submit"
is catchable already from outside the custom component.
I solved by changing the custom event name to filterSubmit
Note also that the type submit on the button - in this use case - is virtually useless, since as default one button in a form will be of type submit.

Manually Triggering jQuery.validate before saving

I have a save button (input button) that I have written javascript code to save the form data to the database. My jQuery .validate function doesn't run before I save the form. How can I manually execute my jQuery .validate function before I save. Here is what I am doing.
<input type="button" class="saveSubmit" name="action" value="Save" />
// Give user feedback when clicking save
$(".saveSubmit").click(function() {
if (save() == true) {
alert("Email has been saved.");
} else {
alert("Error saving email.");
};
return false;
});
// Validation
$("#emailForm").validate({
// rules here
});
Found it. I need to use $("#emailForm").valid().

Trying to check each form input and blank its default value in jquery ajaxform()

I am using the ajaxform() plugin, which so far is working well. However, my input fields have default values, and if the user just submits the untouched form, I need to blank them out before the form is submitted using the beforeSubmit: callback.
In nutshell, I don't know the syntax to check the forms input fields and stop the submit if necessary. I have an idea its using the each() method and this.defaultValue, and maybe a return false? but I'm not sure of the details.
Could anyone perhaps give me an idea? Thanks. Heres my code so far, its the checkValues() function that I'm stuck with.
$(document).ready(function(){
//========= Functions =========
function styleForm() {
$('.quickcontact label').hide();
$('input[type="text"],textarea').addClass("idleField");
$('input[type="text"],textarea').focus(function() {
$(this).removeClass("idleField").addClass("focusField");
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('input[type="text"],textarea').blur(function() {
$(this).removeClass("focusField").addClass("idleField");
if ($.trim(this.value) == ''){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
}
//options for ajaxform() function
var options = {
target: '.quickcontactDisplay', // target element(s) to be updated with server response
beforeSubmit: checkValues, // pre-submit callback
success: reBind // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
//rebinds the ajax functionality to updated form html
function reBind() {
// re-do the form, as it has just been replaced
$('form.quickcontact').ajaxForm(options);
styleForm();
}
//checks for default values of form on submit to prevent them being submitted
function checkValues(){
}
// ==== logic =====
$('form.quickcontact').ajaxForm(options);
styleForm();
});
And my form html:
<form action="/enquiries/add" method="post" id="EnquiryAddForm" class="quickcontact">
<input type="hidden" value="POST" name="_method"/>
<input type="hidden" id="EnquiryVisitorId" value="276" name="data[Enquiry][visitor_id]"/>
<input type="text" id="EnquiryName" maxlength="200" value="Your name" name="data[Enquiry][name]"/>
<input type="text" id="EnquiryEmailAddress" maxlength="200" value="Your Email" name="data[Enquiry][emailAddress]"/>
<textarea id="EnquiryEnquiry" rows="6" cols="30" name="data[Enquiry][enquiry]">Your Email Address</textarea>
<input type="submit" value="Ok, I'm done"/>
</form>
You are abusing the default value as a label. This is causing you problems. Rather then trying to work around those problems, I suggest fixing the cause instead.
When setting default values — set default values. Don't use the default value as a pseudo-label. Use a <label> element instead.
Haven't you looked at the documentation?
beforeSubmit:
Callback function to be invoked before the form is submitted. The
'beforeSubmit' callback can be
provided as a hook for running
pre-submit logic or for validating the
form data. If the 'beforeSubmit'
callback returns false then the form
will not be submitted. The
'beforeSubmit' callback is invoked
with three arguments: the form data in
array format, the jQuery object for
the form, and the Options Object
passed into ajaxForm/ajaxSubmit. The
array of form data takes the following
form:
[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
Default value: null
Here the idea, didn't check it yet.
function checkValues(formData, jqForm, options)
{
for( var i in formData)
if ( formData[i].value == "")
return false;
return true;
}
sounds as if you need to:
run through all the inputs / textarea at the start and grab the default values, then stick it into an associative array with the element id as key
within checkValues, iterate through inputs once again and compare the pre-submit value against your array - when finding a match, you can set the value to "".

Resources