How to pass error message in submit function, enable validation using use form? - forms

1.use useform react hook
2.
3.If data and value.userId below are ===,
I want to re-execute the form validation with an alert or send an error to the userId textfield.
How to do it?
const onsubmit = (value) => {
let data = checkId();
console.log(error);
console.log('데이터', data, '유저아이디', value.userId);
if (data === value.userId) {
alert('중복된 아이디 입니다', data, value.userId);
return;
}
};

Related

Saving ag-grid filter model across page reloads

I have an ag-grid with infinite scroll and data retrieved from an IDatasource.
What I'm trying to do is to save the filter model to session storage when it changes, and then load it and apply it when the grid is reloaded, i.e. when the user leaves the page and then comes back.
I have an onFilterChanged event handler that does
onFilterChanged(params) {
sessionStorage["myFilters"] = JSON.stringify(this.gridApi.getFilterModel());
}
And what I'm trying to do is
onGridReady(params) {
this.gridApi = params.api;
setTimeout(() => {
if(sessionStorage["myFilters"] !== undefined) {
const filters = JSON.parse(sessionStorage["myFilters"]);
this.gridApi.setFilterModel(filters);
}
this.gridApi.setDatasource(this.myDataSource);
}, 0);
}
However, even if the JSON saved to session storage is correct, when getRows is invoked on my IDatasource, its filterModel param has empty values for the filters:
Does this have to do with the fact that my filter is a set filter and the values for the set are loaded dynamically from another API endpoint?
Is there a way to do this?
Turns out I had a bug in my set filter, which was not implementing setModel and getModel properly; the solution was to store the value of the filter in the filter component itself when calling setModel and to check against it when calling getModel:
getModel() {
return {
filter: this.items
.filter((item) => item.checked || item.name === this.selected)
.map((item) => item.name)
.join(),
};
}
setModel(model: any): void {
if (model && model.filter) {
this.selected = model.filter.name || model.filter;
}
}
This way the filter is able to compare the value retrieved from sessionStorage against the existing items, and it works as expected.

How to stop the user from entering the duplicate record on default save

I have a custom module where there is an email field. Now i want to stop the user if the email is already in the database.
I want to stop the user on save button and show the error. Like when a required field goes empty.
I tried to get some help but was not able to understand it.
Note: I realized after posting this that you are using suitecrm which this answer will not be applicable toward but I will leave it in case anyone using Sugar has this question.
There are a couple of ways to accomplish this so I'll do my best to walk through them in the order I would recommend. This would apply if you are using a version of Sugar post 7.0.0.
1) The first route is to manually create an email address relationship. This approach would use the out of box features which will ensure your system only keeps track of a single email address. If that would work for your needs, you can review this cookbook article and let me know if you have any questions:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_the_Email_Field_to_a_Bean/
2) The second approach, where you are using a custom field, is to use field validation. Documentation on field validation can be found here:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/index.html
The code example I would focus on is:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_9.2/Cookbook/Adding_Field_Validation_to_the_Record_View/#Method_1_Extending_the_RecordView_and_CreateView_Controllers
For your example, I would imagine you would do something like this:
Create a language key for your error message:
./custom/Extension/application/Ext/Language/en_us.error_email_exists_message.php
<?php
$app_strings['ERROR_EMAIL_EXISTS_MESSAGE'] = 'This email already exists.';
Create a custom controller for the record creation (you may also want to do this in your record.js):
./custom/modules//clients/base/views/create/create.js
({
extendsFrom: 'RecordView',
initialize: function (options) {
this._super('initialize', [options]);
//reference your language key here
app.error.errorName2Keys['email_exists'] = 'ERROR_EMAIL_EXISTS_MESSAGE';
//add validation tasks
this.model.addValidationTask('check_email', _.bind(this._doValidateEmail, this));
},
_doValidateEmail: function(fields, errors, callback) {
var emailAddress = this.model.get('your_email_field');
//this may take some time so lets give the user an alert message
app.alert.show('email-check', {
level: 'process',
title: 'Checking for existing email address...'
});
//make an api call to a custom (or stock) endpoint of your choosing to see if the email exists
app.api.call('read', app.api.buildURL("your_custom_endpoint/"+emailAddress), {}, {
success: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//analyze your response here
if (response == '<email exists>') {
errors['your_email_field'] = errors['your_email_field'] || {};
errors['your_email_field'].email_exists = true;
}
callback(null, fields, errors);
}, this),
error: _.bind(function (response) {
//dismiss the alert
app.alert.dismiss('email-check');
//throw an error alert
app.alert.show('email-check-error', {
level: 'error',
messages: "There was an error!",
autoClose: false
});
callback(null, fields, errors);
})
});
},
})
Obviously, this isn't a fully working example but it should get you most of the way there. Hope this helps!

Protractor- automate the error message on tab out when input field is empty

I have an angular2 application where I am trying to write end to end test cases to automate things.I have just begun with learning Protractor for this and trying to implement a negative test case for a form field where if any field is empty, the error message should be shown. I have tried something like below to automate the form and its working fine.
In my spec.ts-
import userDetailsPage from './userDetails.e2e-po;
it('should fill out User Details', () => {
const userDetail: IUserDetail = {
firstName: 'Lorem',
lastName: 'Ipsum'
};
userDetailsPage.populateUserDetails(userDetail);
});
In userDetails.e2e-po-
populateUserDetails(details: IUserDetail) {
this.fillFirstName(details.firstName)
.fillLastName(details.lastName)
return this;
}
I am writing the below code which automatically inputs the firstName and lastName field.
fillLastName(last: string) {
let el = element(by.css('input[name="lastName'));
el.clear().then(() => {
el.sendKeys(last);
});
return this;
}
The above scenario works fine. But I am also trying to achieve a scenario where I do not input either first name or last name field, should throw me an error message.Can someone let me know what else should I add to achieve this.
I am already handling the validation in my HTML.
Any help is much appreciated.
Instead of details.firstname and details.lastname put empty strings and then validate the error that occurs on the page.
I think you can try the following method as a reusable function
function formValidate(donefn){
newProjBtn.click().then(async function () {
var lastName_fld = element(by.css('input[name="lastName'));
await lastName_fld.sendKeys("", protractor.Key.TAB);
//browser.sleep(2000);
var elm = element(by.css(".error-message"));
elm.isPresent().then(function(result){
if(result){
console.log("Error message displayed")
//some more code to do like selecting the field and enter the test
return result;
}else{
console.log("Error message not displayed")
return result;
}
})
donefn();
})
I solved it in this way:
await input.sendKeys(protractor.Key.CONTROL, 'a');
await input.sendKeys(protractor.Key.BACK_SPACE);
await input.sendKeys(protractor.Key.TAB);
//then the error-message will appear

Angular2 return data from validation service after Http call

I have build a validation service for my registration form and one of the static methods is checking if the entered email is available by calling my API the following:
static emailAvailable(control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
let valid = "E-mail is available";
http.post('https://secretapi.com/email', JSON.stringify({ email: control.value }))
.map((res: Response) => res.json())
.subscribe(function(result){
if(result.success){
valid = result.success; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return null; //Doesn't do anything?
}else{
valid = result.error; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return { 'invalidEmailAddress': true }; //Doesn't do anything, just like the return above
}
});
console.log(valid); //Output always "E-mail is available"
}
It should return "null" to the form validator when the email is available. The last console.log at the bottom should output the message that it recieves in the subscribe call. This doesn't happen and I'm not sure why. For some reason everything that happens within the subscribe call is contained there and never reaches the validator. What should I change? I have no idea and been searching the web for hours now.
You have to return Observable or Promise from your validator:
return http.post('https://secretapi.com/email', ...
console.log(...) doesn't make any sense here, since it will be executed after the Observable has been created as an object, but not after the ajax call has bee made.
If you want to output something after a response has been received, you have to move it inside subscribe
So in the end this website had the right answer. Also important to notice with the Angular2 Form validator to put the Async validators in the third (3) parameter and not together in an array in the second (2) parameter. That took me about 3 hours to figure out.
function checkEmail(control: Control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
return new Observable((obs: any) => {
control
.valueChanges
.debounceTime(400)
.flatMap(value => http.post('https://secretapi.com/email', JSON.stringify({ email: control.value })))
.map((res: Response) => res.json())
.subscribe(
data => {
if(data.success){
obs.next(null);
obs.complete();
} else {
obs.next({ 'invalidEmailAddress': true });
obs.complete();
}
}
);
});
}
The validator should look something like this, with the first validators checking on required and if it's actually an email address and the last doing an async call to the server to see if it's not already in use:
this.registerForm = this.formBuilder.group({
'email': ['', [Validators.required, ValidationService.emailValidator], ValidationService.emailAvailable],
});

Zend Dojo. Ajax submit dojo form

How to submit dojo form using AJAX and if there are errors, print errors near incorrectly filled fields?
Now I am doing something like that:
dojo.ready(function() {
var form = dojo.byId("user_profile_form");
dojo.connect(form, "onsubmit", function(event){
dojo.stopEvent(event);
var xhrArgs = {
form: form,
handleAs: "json",
load: function(responseText){
var result_data = zen.json.getResult(responseText);
dojo.byId("response").innerHTML = "Form posted.";
},
error: function(error){
// We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
// docs server.
dojo.byId("response").innerHTML = "Form posted.";
}
}
// Call the asynchronous xhrPost
dojo.byId("response").innerHTML = "Form being sent..."
var deferred = dojo.xhrPost(xhrArgs);
});
But I don't know how to print errors
There are a few ways that you can do this. The one that I prefer is to subscribe to the IO Pipeline Topics
For errors, subscribe to the /dojo/io/error topic. Here's an example that will Growl the errors.
dojo.subscribe("/dojo/io/error", function(/*dojo.Deferred*/ dfd, /*Object*/ error){
// Triggered whenever an IO request has errored.
// It passes the error and the dojo.Deferred
// for the request with the topic.
var responseTextObject = dojo.fromJson(error.responseText)
var growlMessage = '';
if (responseTextObject && responseTextObject.message) {
growlMessage += responseTextObject.message
} else {
// Don't Growl the xhr cancelled messages.
if (error.message == 'xhr cancelled') {
return;
}
growlMessage = error.message
}
new ext.Growl({
message: growlMessage
});
});
The server should provide all the error details in the response. In this example, a JSON formatted response is expected but if it's not provided, the error is still shown.
If you want to see the nice invalid field styling, put the widgets in a dijit.form.Form